首页 > 解决方案 > 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)

标签: pythonpandasmulti-indexkeyerror

解决方案


推荐阅读