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

其他回答

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

使用迭代

 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

只需使用此功能

我发现这种方法非常有用:

# iloc[row slicing, column slicing]
surveys_df.iloc [0:3, 1:4]

更多详情请点击此处。

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

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

对于Pandas,

具有列名称

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

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

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

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

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