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

当前回答

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

使用迭代

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

其他回答

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

从0.21.0开始,在列表中使用.loc或[](其中包含一个或多个缺失的标签)是不推荐使用.reindex的。因此,问题的答案是:

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

在以前的版本中,只要找到至少一个键,就可以使用.loc〔标签列表〕(否则会引发KeyError)。此行为已弃用,现在显示警告消息。建议使用.reindex()。

阅读更多关于索引和选择数据的信息。

列名(字符串)无法按您尝试的方式进行切片。

这里有两个选项。如果您从上下文中知道要分割哪些变量,只需通过将列表传递到__getitem_语法([])中,即可返回这些列的视图。

df1 = df[['a', 'b']]

或者,如果重要的是对它们进行数字索引,而不是按它们的名称进行索引(假设您的代码应该在不知道前两列的名称的情况下自动进行索引),那么您可以改为这样做:

df1 = df.iloc[:, 0:2] # Remember that Python does not slice inclusive of the ending index.

此外,您应该熟悉Pandas对象视图与该对象副本的概念。上述第一个方法将在内存中返回所需子对象(所需切片)的新副本。

然而,有时Pandas中有一些索引约定不这样做,而是给你一个新变量,它只引用与原始对象中的子对象或切片相同的内存块。这将发生在第二种索引方式中,因此您可以使用.copy()方法对其进行修改以获得常规副本。当发生这种情况时,更改您认为的切片对象有时会更改原始对象。时刻注意这一点总是很好的。

df1 = df.iloc[0, 0:2].copy() # To avoid the case where changing df1 also changes df

要使用iloc,您需要知道列位置(或索引)。由于列位置可能会改变,您可以使用iloc和dataframe对象的columns方法的get_loc函数来获取列索引,而不是硬编码索引。

{df.columns.get_loc(c): c for idx, c in enumerate(df.columns)}

现在,您可以使用此字典通过名称和iloc访问列。

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

使用迭代

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