Skip to main content
 首页 » 编程设计

Python Pandas : dataframe. loc 返回 "KeyError: label not in [index]",但 dataframe.index 显示它是

2025年05月04日22arxive

我在 Python 中使用 pandas 工具包,但遇到问题。

我有一个值列表 lst ,为了简单起见,假设它只有前 20 个自然数:

>>> lst = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] 

然后我创建一个 DataFrame ,通过给它一个带有该列表的 Series ,如下所示:

>>> df = DataFrame(Series(lst)) 

我想用它来计算从 0.1 (10%) 到 1 (100%) 的分位数,我使用 DataFrame 中的 quantile 函数来计算:

>>> quantiles = df.quantile(np.linspace(.1,1,num=10,endpoint=True)) 

如果我打印 quantiles ,这就是出现的内容:

        0 
0.1   2.9 
0.2   4.8 
0.3   6.7 
0.4   8.6 
0.5  10.5 
0.6  12.4 
0.7  14.3 
0.8  16.2 
0.9  18.1 
1.0  20.0 

现在,我想将分位数 0.3 和 0.7 的值存储在一个变量中,在搜索了如何做到这一点之后,我想出了一个使用 loc 的解决方案在 DataFrame 中,给它分位数标签(例如 0.7 )和我要考虑的一系列值的列索引。因为只有一个,所以我这样做:

>>> q_3 = qts.loc[0.7][0] 

问题是 python 给我这个错误:

**KeyError: 'the label [0.7] is not in the [index]'** 

但我知道它存在,因为如果我尝试打印 index 值,我会得到:

>>> qts.index 
Float64Index([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0], dtype='float64') 

所以,索引显然存在,但我说它不存在。 我做错了什么?

如果我尝试使用这种方法打印任何其他分位数值,而不是 0.3 或 0.7 ,它会起作用:

>>> qts.loc[0.1][0] 
2.8999999999999999 
>>> qts.loc[0.2][0] 
4.8000000000000007 
>>> qts.loc[0.4][0] 
8.6000000000000014 
>>> qts.loc[0.5][0] 
10.5 
>>> qts.loc[0.6][0] 
12.4 
>>> qts.loc[0.8][0] 
16.200000000000003 
>>> qts.loc[0.9][0] 
18.100000000000001 
>>> qts.loc[1][0] 
20.0 

有什么想法吗?

我使用的是 Python 3.5 和 pandas 0.20.3。

编辑 感谢您的反馈! 所以,这是一个浮点精度问题。不过,我想知道:是否有更好的方法来获取分位数列表的 N'th 元素,而不是像我那样使用 loc?

请您参考如下方法:

这里的索引值不是正好等于0.7;在非常小的精度上存在差异。您可以通过运行来确认这一点:

assert qts.index[6] == 0.7 

或

print(qts.index[6] - 0.7) 

如果您首先使用 numpy.round 舍入索引,您将能够根据需要通过 qts.loc[0.7, 0] 访问该元素:

import numpy as np 
 
qts.index = np.round(qts.index, decimals=1)