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
相关产品推荐
相关产品推荐

