如何从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['b'][0]一样执行。这就像你能想象的那样简单。

或者可以使用df.ix[0,'b']-索引和标签的混合用法。

注意:从v0.20开始,ix已被弃用,取而代之的是loc/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()
def get_slize(dataframe, start_row, end_row, start_col, end_col):
    assert len(dataframe) > end_row and start_row >= 0
    assert len(dataframe.columns) > end_col and start_col >= 0
    list_of_indexes = list(dataframe.columns)[start_col:end_col]
    ans = dataframe.iloc[start_row:end_row][list_of_indexes]
    return ans

只需使用此功能

对于Pandas,

具有列名称

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

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

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

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

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

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