我有一个 float 列表(实际上它是一个 pandas Series 对象,如果它改变了什么)看起来像这样:
mySeries:
...
22 16.0
23 14.0
24 12.0
25 10.0
26 3.1
...
(所以这个 Series 的元素在右边,索引在左边。)然后我尝试将这个 Series 中的元素分配为字典中的键,并将索引分配为值,如下所示:
{ mySeries[i]: i for i in mySeries.index }
我几乎得到了我想要的,除了......
{ 6400.0: 0, 66.0: 13, 3.1000000000000001: 23, 133.0: 10, ... }
为什么 3.1
突然变成了 3.1000000000000001
?我想这与 float 的表示方式有关(?),但为什么现在会发生这种情况,我该如何避免/修复它?
编辑:如果这个问题不准确,请随时为这个问题建议一个更好的标题。
EDIT2: 好的,看起来是完全相同的数字,只是打印不同。不过,如果我将 mySeries[26]
指定为字典键,然后尝试运行:
myDict[mySeries[26]]
我收到 KeyError
。避免它的最佳方法是什么?
最佳答案
字典并没有改变 3.1 的浮点表示法,但它实际上显示了完整的精度。您打印的 mySeries[26] 正在截断精度并显示近似值。
你可以证明这一点:
pd.set_option('precision', 20)
然后查看我的系列。
0 16.00000000000000000000
1 14.00000000000000000000
2 12.00000000000000000000
3 10.00000000000000000000
4 3.10000000000000008882
dtype: float64
编辑:
What every computer programmer should know about floating point arithmetic总是一本好书。
编辑:
关于 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
关于python - 将 float 分配为字典键会改变其精度 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39901833/