如何从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,并将它们保存到新的数据帧df1中?
index a b c
1 2 3 4
2 3 4 5
尝试失败:
df1 = df['a':'b']
df1 = df.ix[:, 'a':'b']
当前回答
您可以提供要删除的列的列表,并使用Pandas DataFrame上的drop()函数仅返回所需的列。
只是说说而已
colsToDrop = ['a']
df.drop(colsToDrop, axis=1)
将返回仅包含列b和c的DataFrame。
此处记录了drop方法。
其他回答
我发现这种方法非常有用:
# iloc[row slicing, column slicing]
surveys_df.iloc [0:3, 1:4]
更多详情请点击此处。
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
在最新版本的Pandas中,有一种简单的方法可以做到这一点。列名(字符串)可以按您喜欢的方式进行切片。
columns = ['b', 'c']
df1 = pd.DataFrame(df, columns=columns)
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
只需使用此功能
如果要按行索引和列名获取一个元素,可以像df['b'][0]一样执行。这就像你能想象的那样简单。
或者可以使用df.ix[0,'b']-索引和标签的混合用法。
注意:从v0.20开始,ix已被弃用,取而代之的是loc/iloc。