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

del df['column_name']

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

del df.column_name

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


当前回答

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

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

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

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

其他回答

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

按索引删除

删除第一列、第二列和第四列:

df.drop(df.columns[[0,1,3]], axis=1, inplace=True)

删除第一列:

df.drop(df.columns[[0]], axis=1, inplace=True)

此处有一个可选参数可以在不创建副本的情况下修改数据。

被逮捕的

列选择、添加、删除

删除列列名:

df.pop('column-name')

示例:

df = DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6]), ('C', [7,8, 9])], orient='index', columns=['one', 'two', 'three'])

打印df:

   one  two  three
A    1    2      3
B    4    5      6
C    7    8      9

df.drop(df.columns[[0],axis=1,inplace=True)打印df:

   two  three
A    2      3
B    5      6
C    8      9

三=df.pop(“三”)打印df:

   two
A    2
B    5
C    8

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)

要删除特定列之前和之后的列,可以使用truncate方法。例如:

   A   B    C     D      E
0  1  10  100  1000  10000
1  2  20  200  2000  20000

df.truncate(before='B', after='D', axis=1)

输出:

    B    C     D
0  10  100  1000
1  20  200  2000

点语法在JavaScript中有效,但在Python中无效。

Python:del df['column_name]JavaScript:del df['column_name]或del df.column_name