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

当前回答

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

其他回答

也可以使用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.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数组,用于按标签查找列。

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

   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

一种不同且简单的方法:迭代行

使用迭代

 df1 = pd.DataFrame() # Creating an empty dataframe
 for index,i in df.iterrows():
    df1.loc[index, 'A'] = df.loc[index, 'A']
    df1.loc[index, 'B'] = df.loc[index, 'B']
    df1.head()

尝试使用pandas.DataFrame.get(请参阅文档):

import pandas as pd
import numpy as np

dates = pd.date_range('20200102', periods=6)
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))
df.get(['A', 'C'])