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

当前回答

在最新版本的Pandas中,有一种简单的方法可以做到这一点。列名(字符串)可以按您喜欢的方式进行切片。

columns = ['b', 'c']
df1 = pd.DataFrame(df, columns=columns)

其他回答

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

   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

假设你的列名(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数组,用于按标签查找列。

您可以提供要删除的列的列表,并使用Pandas DataFrame上的drop()函数仅返回所需的列。

只是说说而已

colsToDrop = ['a']
df.drop(colsToDrop, axis=1)

将返回仅包含列b和c的DataFrame。

此处记录了drop方法。

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

我认为这是实现目标的最简单方法。

熊猫作为pd进口列=[a','b']df1=pd.DataFrame(df,columns=cols)df1=df.iloc[:,0:2]