我正在尝试将 pandas DataFrame 转换为字典列表,其中 1 个字典代表 1 行;因此 pandas to_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')
似乎工作正常。这里有什么问题吗?
最佳答案
在 pandas 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 float 转换回原生 python float 时:
print(float(records[0]['x']))
0.333
我们得到的输出类似于面向 to_records 输出的列表。
有关奇怪的 float 恶作剧的更多信息 Is floating point math broken?
关于pandas: to_dict ("records") 舍入不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45065253/