You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas DataFrame筛选含'All'的索引时出现KeyError: 'index'报错求助

解决Pandas筛选索引包含"All"行的KeyError问题

你遇到的KeyError: 'index'问题原因很直接——你想用pivot_device_T['index']访问DataFrame的行索引,但Pandas里[]操作符是用来访问列的,你的DataFrame根本没有名为index的列,自然会触发报错。

你的目标是筛选行索引(名称为operatorName)中包含"All"的行,这里有几种简单高效的正确写法:

方法一:直接操作行索引

直接通过pivot_device_T.index访问行索引,调用str.contains()方法完成筛选:

pivot_device_T = pivot_device_T[pivot_device_T.index.str.contains("All")]

方法二:使用query方法(更简洁)

因为你的行索引有明确名称operatorName,可以直接在query语句里引用这个名称:

pivot_device_T = pivot_device_T.query("operatorName.str.contains('All')")

方法三:索引转列后筛选(可选思路)

如果你更习惯操作列,也可以先把索引转为普通列,筛选完成后再恢复索引,不过这种方法没必要,仅作为拓展思路:

# 将行索引转为普通列,列名就是索引的名称operatorName
pivot_device_T = pivot_device_T.reset_index()
# 筛选包含"All"的行
pivot_device_T = pivot_device_T[pivot_device_T['operatorName'].str.contains("All")]
# 将列重新设为行索引
pivot_device_T = pivot_device_T.set_index('operatorName')

这样就能顺利筛选出所有索引包含"All"的行啦!

内容的提问来源于stack exchange,提问作者Nabih Bawazir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:40:07