mac*_*rus 4 python floating-point dictionary pandas
我有一个浮动列表(实际上它是一个pandas Series对象,如果它改变了什么),它看起来像这样:
mySeries:
...
22 16.0
23 14.0
24 12.0
25 10.0
26 3.1
...
Run Code Online (Sandbox Code Playgroud)
(因此,本系列的元素位于右侧,左侧是索引.)然后,我尝试将此系列中的元素指定为字典中的键,将索引指定为值,如下所示:
{ mySeries[i]: i for i in mySeries.index }
Run Code Online (Sandbox Code Playgroud)
而且我得到了我想要的东西,除了......
{ 6400.0: 0, 66.0: 13, 3.1000000000000001: 23, 133.0: 10, ... }
Run Code Online (Sandbox Code Playgroud)
为什么3.1突然变成了3.1000000000000001?我想这与浮点数的表示方式有关(?),但为什么现在会发生,我该如何避免/修复呢?
编辑:如果这个问题不准确,请随时为这个问题建议一个更好的标题.
编辑2:好的,所以它似乎是完全相同的数字,只是印刷方式不同.仍然,如果我指定mySeries[26]为字典键,然后我尝试运行:
myDict[mySeries[26]]
Run Code Online (Sandbox Code Playgroud)
我得到KeyError.什么是避免它的最佳方法?
该值在该系列中已经是这样的:
>>> x = pd.Series([16,14,12,10,3.1])
>>> x
0 16.0
1 14.0
2 12.0
3 10.0
4 3.1
dtype: float64
>>> x.iloc[4]
3.1000000000000001
Run Code Online (Sandbox Code Playgroud)
这与浮点精度有关:
>>> np.float64(3.1)
3.1000000000000001
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅Python 数组中的浮点精度。
关于KeyError您的编辑,我无法重现。请参阅以下内容:
>>> d = {x[i]:i for i in x.index}
>>> d
{16.0: 0, 10.0: 3, 12.0: 2, 14.0: 1, 3.1000000000000001: 4}
>>> x[4]
3.1000000000000001
>>> d[x[4]]
4
Run Code Online (Sandbox Code Playgroud)
我的怀疑是KeyError来自Series:返回的是什么mySeries[26]?
字典不会改变3.1的浮点表示,但它实际上显示了完整的精度.你的mySeries [26]的打印正在截断精度并显示近似值.
你可以证明这一点:
pd.set_option('precision', 20)
Run Code Online (Sandbox Code Playgroud)
然后查看mySeries.
0 16.00000000000000000000
1 14.00000000000000000000
2 12.00000000000000000000
3 10.00000000000000000000
4 3.10000000000000008882
dtype: float64
Run Code Online (Sandbox Code Playgroud)
编辑:
每个计算机程序员应该知道的浮点运算总是一个很好的阅读.
编辑:
关于KeyError,我无法复制问题.
>> x = pd.Series([16,14,12,10,3.1])
>> a = {x[i]: i for i in x.index}
>> a[x[4]]
4
>> a.keys()
[16.0, 10.0, 3.1000000000000001, 12.0, 14.0]
>> hash(x[4])
2093862195
>> hash(a.keys()[2])
2093862195
Run Code Online (Sandbox Code Playgroud)