熊猫:to_dict("records")舍入不正确



我正在尝试将熊猫数据帧转换为字典列表,其中 1 个字典代表 1 行;因此 pandasto_dict(orient='records')方法是完美的;但是在某些情况下输出不正确地四舍五入。下面是一个示例:

df = pd.DataFrame({'x': [1/3, 2/3], y=[4/3, 5/3]})
#            x         y
0  0.333333  1.333333
1  0.666667  1.666667
df.round(3).to_dict(orient='records')  # rounded incorrectly
# [{'x': 0.3330000000000002, 'y': 1.333}, {'x': 0.6670000000000004, 'y': 1.667}]
df.round(3).to_dict(orient='list')  # rounded correctly
# {'x': [0.333, 0.667], 'y': [1.333, 1.667]}

如您所见to_dict(orient='list')似乎工作正常。这里有什么问题?

在熊猫 0.20.2 中,由于某种原因,orient = records使用 numpy float 类型,而orient = list使用 native python float 类型。

records = df.round(3).to_dict(orient='records')
print(type(records[0]['x']))
numpy.float64
list_orient=df.round(3).to_dict(orient='list')
print(type(list_orient['x'][0]))
float

确切数据类型的差异会导致舍入差异。 现在为什么不同的定向参数会导致不同的数据类型,我不能说。

将 numpy 浮点数转换回本机 python 浮点数时:

print(float(records[0]['x']))
0.333

我们得到的输出就像在面向to_records输出的列表一样。

有关奇怪的浮点恶作剧的更多信息浮点数学坏了吗?

最新更新