python - 为什么 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
解决方案
当 时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 相当于列=标签)。
推荐阅读
- google-cloud-platform - 当自定义日志消息传送到 GCP Stackdriver 时发送通知
- javascript - 如何通过表单提交保持 Chrome 扩展在页面重新加载时运行?
- r - 闪亮的 fileInput() 对多个文件选择没有反应
- android - Android导航组件:以编程方式从与家不同的目的地开始?
- vba - 是否需要 VBA 才能根据组合框中的名称运行 SQL 查询?
- sql - 在同一个表的两列中查找值相同的数据
- amazon-web-services - 如何将 Spring Cloud Function 连续部署到 AWS lambda
- javascript - 如何使用 getusermedia 从多个后置摄像头检测主/长焦摄像头
- java - 如何从另一个控制器操作 TableView?
- node.js - 运行 vue-cli-service serve 时来自 Node.js 的高 CPU 使用率