如何从df中选择列a和b,并将它们保存到新的数据帧df1中?

index  a   b   c
1      2   3   4
2      3   4   5

尝试失败:

df1 = df['a':'b']
df1 = df.ix[:, 'a':'b']

当前回答

我发现这种方法非常有用:

# iloc[row slicing, column slicing]
surveys_df.iloc [0:3, 1:4]

更多详情请点击此处。

其他回答

对于Pandas,

具有列名称

dataframe[['column1','column2']]

要通过iloc和带有索引编号的特定列进行选择,请执行以下操作:

dataframe.iloc[:,[1,2]]

带有loc的列名可以使用如下

dataframe.loc[:,['column1','column2']]

假设你的列名(df.columns)是['index','a','b','c'],那么你想要的数据就在第三列和第四列。如果脚本运行时不知道它们的名称,可以执行以下操作

newdf = df[df.columns[2:4]] # Remember, Python is zero-offset! The "third" entry is at slot two.

正如EMS在回答中所指出的,df.ix对列进行了更简洁的切片,但.columns切片接口可能更自然,因为它使用了普通的一维Python列表索引/切片语法。

警告:“index”是DataFrame列的错误名称。同一标签也用于实际df.index属性,即index数组。因此,您的列由df['index']返回,而真正的DataFrame索引由df.index返回。index是一种特殊的系列,优化用于查找其元素值。对于df.index,它用于按标签查找行。df.columns属性也是一个pd.Index数组,用于按标签查找列。

从0.11.0版起,可以使用.loc索引器以尝试的方式对列进行切片:

df.loc[:, 'C':'E']

相当于

df[['C', 'D', 'E']]  # or df.loc[:, ['C', 'D', 'E']]

并返回列C到E。


随机生成的DataFrame演示:

import pandas as pd
import numpy as np
np.random.seed(5)
df = pd.DataFrame(np.random.randint(100, size=(100, 6)),
                  columns=list('ABCDEF'),
                  index=['R{}'.format(i) for i in range(100)])
df.head()

Out:
     A   B   C   D   E   F
R0  99  78  61  16  73   8
R1  62  27  30  80   7  76
R2  15  53  80  27  44  77
R3  75  65  47  30  84  86
R4  18   9  41  62   1  82

要获取从C到E的列(请注意,与整数切片不同,列中包含E):

df.loc[:, 'C':'E']

Out:
      C   D   E
R0   61  16  73
R1   30  80   7
R2   80  27  44
R3   47  30  84
R4   41  62   1
R5    5  58   0
...

这同样适用于基于标签选择行。从这些列中获取行R6到R10:

df.loc['R6':'R10', 'C':'E']

Out:
      C   D   E
R6   51  27  31
R7   83  19  18
R8   11  67  65
R9   78  27  29
R10   7  16  94

.loc还接受布尔数组,因此您可以选择数组中相应条目为True的列。例如,df.columns.isin(list('BCD'))返回array([False,True,True,False,False,False],dtype=bool)-如果列名在列表['B','C','D']中,则返回True;否则为False。

df.loc[:, df.columns.isin(list('BCD'))]

Out:
      B   C   D
R0   78  61  16
R1   27  30  80
R2   53  80  27
R3   65  47  30
R4    9  41  62
R5   78   5  58
...

也可以使用df.pop():

>>> df = pd.DataFrame([('falcon', 'bird',    389.0),
...                    ('parrot', 'bird',     24.0),
...                    ('lion',   'mammal',   80.5),
...                    ('monkey', 'mammal', np.nan)],
...                   columns=('name', 'class', 'max_speed'))
>>> df
     name   class  max_speed
0  falcon    bird      389.0
1  parrot    bird       24.0
2    lion  mammal       80.5
3  monkey  mammal

>>> df.pop('class')
0      bird
1      bird
2    mammal
3    mammal
Name: class, dtype: object

>>> df
     name  max_speed
0  falcon      389.0
1  parrot       24.0
2    lion       80.5
3  monkey        NaN

请使用df.pop(c)。

def get_slize(dataframe, start_row, end_row, start_col, end_col):
    assert len(dataframe) > end_row and start_row >= 0
    assert len(dataframe.columns) > end_col and start_col >= 0
    list_of_indexes = list(dataframe.columns)[start_col:end_col]
    ans = dataframe.iloc[start_row:end_row][list_of_indexes]
    return ans

只需使用此功能