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

del df['column_name']

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

del df.column_name

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


当前回答

按索引删除

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

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

其他回答

在Pandas 0.16.1+中,只有当列按照eiTan LaVi发布的解决方案存在时,才能删除它们。在此版本之前,您可以通过条件列表理解获得相同的结果:

df.drop([col for col in ['col_name_1','col_name_2',...,'col_name_N'] if col in df],
        axis=1, inplace=True)

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

正如您所猜测的,正确的语法是

del df['column_name']

由于Python中的语法限制,很难使del df.column_name正常工作。deldf[name]被翻译成df__delitem__(name)在Python的封面下。

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

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