多索引中出现意外的键错误

2024-05-21 00:23:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: inpandasdfindexfoo错误line整数