python - Pandas 多索引中的意外键错误
问题描述
仅当列名称为整数值 0(与字符“0”相反)时,才会出现该错误。例如:
df = pd.DataFrame({
1:[7,3,2,1,2],
'Foo':['A', 'A', 'A', 'B', 'B'],
'0':[2,4,6,8,10],
'3':['1','2','3','4','5']
})
In [232]: df.set_index(['Foo', '0']).loc[('A',2)]
Out[232]:
1 7
3 1
Name: (A, 2), dtype: object
在这种情况下,列 1 和 '3' 的值被正确返回,但是如果我将第三列的名称从 '0' 更改为 0,查询将返回键错误;即使多索引看起来是正确的。
dg = pd.DataFrame({
1:[7,3,2,1,2],
'Foo':['A', 'A', 'A', 'B', 'B'],
0:[2,4,6,8,10],
'3':['1','2','3','4','5']
})
In[245]: dg.set_index(['Foo', 0])
Out[245]:
1 3
Foo 0
A 2 7 1
4 3 2
6 2 3
B 8 1 4
10 2 5
In[246]: dg.set_index(['Foo', 0]).loc[('A',2)]
Out[246]:
Traceback (most recent call last):
. . .
File "pandas/_libs/index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 128, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index_class_helper.pxi", line 91, in pandas._libs.index.Int64Engine._check_type
KeyError: 'A'
当我使用列 'Foo' 和 1 来索引数据框时,不会引发关键错误:
df.set_index(['Foo', 1]).loc[('A',2)]
Out[237]:
0 6
3 3
Name: (A, 2), dtype: object
任何见解都会有所帮助,因为我的用例需要具有整数列名的数据框。
我正在使用熊猫版本:0.25.3 和 Python 版本:3.7.4
在 Ubuntu 18.04 上的 IPython 环境(版本 7.10.1,通过 anaconda/spyder)
解决方案
推荐阅读
- python - 使用 XLRD 从另一个 excel 文件中读取值
- php - 按升序获取最近 6 个月
- c# - 如何在光标位置裁剪图像的一部分?
- java - 从双数组中获取最小值不起作用
- jasper-reports - 如何使用 iReport 渲染单个 JRDatasource 的特定子集?
- c# - 继承两个类,分别从接口实现
- mysql - 在这种情况下我是否使用命令“sum”?
- java - 使用 DMSDK 从 Marklogic 批量摄取数据到 RDBMS
- c# - 控制器文件不会出现在项目中
- javascript - 错误:警告:setState(...):在现有状态转换期间无法更新(例如在 `render` 或另一个组件的构造函数中)