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

其他回答

In [39]: df
Out[39]: 
   index  a  b  c
0      1  2  3  4
1      2  3  4  5

In [40]: df1 = df[['b', 'c']]

In [41]: df1
Out[41]: 
   b  c
0  3  4
1  4  5

前面的答案中讨论的不同方法基于这样的假设:用户知道要删除或子集的列索引,或者用户希望使用一系列列(例如“C”和“E”之间)来子集数据帧。

pandas.DataFrame.drop()当然是一个基于用户定义的列列表对数据进行子集的选项(尽管您必须谨慎地始终使用数据帧的副本,并且不应将就地参数设置为True!!)

另一个选项是使用pandas.columns.difference(),它对列名进行设置差异,并返回包含所需列的数组的索引类型。以下是解决方案:

df = pd.DataFrame([[2,3,4], [3,4,5]], columns=['a','b','c'], index=[1,2])
columns_for_differencing = ['a']
df1 = df.copy()[df.columns.difference(columns_for_differencing)]
print(df1)

输出将是:

    b   c
1   3   4
2   4   5

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

df1 = df.filter(['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

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

使用迭代

 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()