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

del df['column_name']

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

del df.column_name

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


当前回答

如果原始数据帧df不太大,没有内存限制,只需要保留几列,或者,如果事先不知道不需要的所有额外列的名称,那么不妨创建一个只包含所需列的新数据帧:

new_df = df[['spam', 'sausage']]

其他回答

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)

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

del df['column_name']

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

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

如果原始数据帧df不太大,没有内存限制,只需要保留几列,或者,如果事先不知道不需要的所有额外列的名称,那么不妨创建一个只包含所需列的新数据帧:

new_df = df[['spam', 'sausage']]

要删除特定列之前和之后的列,可以使用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