要删除DataFrame中的列,我可以成功使用:

del df['column_name']

但为什么我不能使用以下选项?

del df.column_name

由于可以通过df.column_name访问该系列,所以我希望这能奏效。


当前回答

在Pandas中执行此操作的最佳方法是使用drop:

df = df.drop('column_name', axis=1)

其中1是轴号(0表示行,1表示列。)

或者,drop()方法接受索引/列关键字作为指定轴的替代方法。所以我们现在可以做:

df = df.drop(columns=['column_nameA', 'column_nameB'])

这是在v0.21.0中引入的(2017年10月27日)

要删除列而不必重新分配df,可以执行以下操作:

df.drop('column_name', axis=1, inplace=True)

最后,要按列编号而不是按列标签删除,请尝试删除,例如,第1列、第2列和第4列:

df = df.drop(df.columns[[0, 1, 3]], axis=1)  # df.columns is zero-based pd.Index

同时使用列的“text”语法:

df.drop(['column_nameA', 'column_nameB'], axis=1, inplace=True)

其他回答

Use:

columns = ['Col1', 'Col2', ...]
df.drop(columns, inplace=True, axis=1)

这将在位删除一个或多个列。请注意,inplace=True是在panda v0.13中添加的,在旧版本中不起作用。在这种情况下,您必须重新分配结果:

df = df.drop(columns, axis=1)

一个很好的补充是,只有列存在时才可以删除它们。这样,您可以覆盖更多的用例,并且它只会从传递给它的标签中删除现有列:

例如,只需添加errors='ignore':

df.drop(['col_name_1', 'col_name_2', ..., 'col_name_N'], inplace=True, axis=1, errors='ignore')

这是熊猫0.16.1以后的新版本。文档在这里。

通过使用自动补全或“IntelliSense”而不是字符串文字来获得优势:

del df[df.column1.name]

# or

df.drop(df.column1.name, axis=1, inplace=True)

它适用于当前的Pandas版本。

从版本0.16.1开始,您可以

df.drop(['column_name'], axis = 1, inplace = True, errors = 'ignore')

Use:

df.drop('columnname', axis =1, inplace = True)

或者你可以和

del df['colname']

基于列编号删除多个列的步骤

df.drop(df.iloc[:,1:3], axis = 1, inplace = True)

基于列名删除多个列的步骤

df.drop(['col1','col2',..'coln'], axis = 1, inplace = True)