熊猫多索引中的意外键错误

时间:2020-01-07 17:27:12

标签: python pandas multi-index keyerror

仅当列名是整数值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

在IPython环境中(版本7.10.1,通过anaconda / spyder)

在Ubuntu 18.04上

0 个答案:

没有答案