如何从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']

当前回答

从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
...

其他回答

对于Pandas,

具有列名称

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

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

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

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

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

您可以使用pandas.DataFrame.filter方法对列进行筛选或重新排序,如下所示:

df1 = df.filter(['a', 'b'])

这在链接方法时也非常有用。

也可以使用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)。

df[['a', 'b']]  # Select all rows of 'a' and 'b'column 
df.loc[0:10, ['a', 'b']]  # Index 0 to 10 select column 'a' and 'b'
df.loc[0:10, 'a':'b']  # Index 0 to 10 select column 'a' to 'b'
df.iloc[0:10, 3:5]  # Index 0 to 10 and column 3 to 5
df.iloc[3, 3:5]  # Index 3 of column 3 to 5

若要排除某些列,可以将它们放在列索引中。例如:

   A   B    C     D
0  1  10  100  1000
1  2  20  200  2000

选择除两个以外的所有选项:

df[df.columns.drop(['B', 'D'])]

输出:

   A    C
0  1  100
1  2  200

也可以使用truncate方法选择中间列:

df.truncate(before='B', after='C', axis=1)

输出:

    B    C
0  10  100
1  20  200