首页 > 解决方案 > 为什么 DataFrame.drop() 不适用于列方式(轴 = 1)?

问题描述

我生成了一个数据框并尝试删除第二列,但代码仅适用于行(axis = 0)而不适用于列(axis = 1),想知道为什么?

data1 ={"Name":pd.Series(['Sam','Paul','Jim']), 
      "Score1":pd.Series([100, 90, 85]), 
      "Score2":pd.Series([80, 85, 90])}

df1 = pd.DataFrame(data1)

df1.drop(1, axis = 1, inplace = True)
print(df1)

这会不断生成一条错误消息,KeyError: '[1] not found in axis

标签: pythonpandasdataframe

解决方案


当 时axis=0,第一个参数是index要删除的。index如索引的名称(熊猫术语中的“标签”),而不是行的索引。

同样,当axis=1第一个参数是要删除的列的名称时,而不是列的索引。

df1.drop(1, axis=1, inplace=True)

应该

df1.drop('Score1', axis=1, inplace=True)

或者,使用更明确的方式使用columns参数:

df1.drop(columns='Score1', inplace=True)

所有这些都包含在文档中:

标签,单个标签或类似列表的索引或列标签要删除。

axis, {0 or 'index', 1 or 'columns'}, 默认0 是否从索引(0或'index')或列(1或'columns')中删除标签。

index, single label or list-like 指定轴的替代方案(标签,axis=0 等价于 index=labels)。

列,单个标签或类似列表的替代指定轴(标签,轴= 1 相当于列=标签)。


推荐阅读