gpt4 book ai didi

python - to_json() 函数错误地导出了带有 float64 的 Pandas 数据框

转载 作者:行者123 更新时间:2023-12-03 19:08:44 25 4
gpt4 key购买 nike

这个问题是关于使用 Pandas 的 to_json() 函数导出具有 float64 数据类型的数据帧。源代码附在下面。

import pandas

if __name__ == "__main__":
d = {'col1': [11111111.84, 123456.55], 'col2': [3, 4]}
df = pandas.DataFrame(data=d)

print(df)
print(df.dtypes)

output_file_path = '/test.csv'
df.to_csv(output_file_path, index=False, encoding='UTF-8')
output_file_path = '/test.json'
df.to_json(output_file_path, orient="records", lines=True)
在将数据帧导出为 JSON 或 CSV 文件之前, print() 函数的输出是正确的。输出如下所示。
          col1  col2
0 11111111.84 3
1 123456.55 4
col1 float64
col2 int64
dtype: object
以 CSV 格式 (test.csv) 导出的数据是正确的。
enter image description here
JSON 格式 (test.json) 导出的数据有 错误 小数点如下图 col1 row1 (11111111.8399999999) _0x10456792此问题仅对某些值发生,因为 col1 row2 是正确的 (123456.55)。
enter image description here
我发现有一种解决方法可以通过为 double_precision 函数指定另一个参数 to_json() 来解决此问题。结果变得正确! (已经测试过了。)
引用:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.html
但是,通过指定 double_precision 参数,它可能会限制所有列的小数点数。当每个数据列需要不同数量的小数点时,这不是一个好方法。
另外,找到了下面的主题,但不确定它是否与我的这个问题有关。
链接:What is the difference between NUMERIC and FLOAT in BigQuery?
我正在尝试了解此问题的根本原因并寻找解决方案。这很奇怪,这个问题只发生在 to_json() 函数上,但 to_csv() 函数有效。
任何人请帮忙!

最佳答案

pandas to_json 可能在那里做一些奇怪的事情。正如您所解释的,规范的解决方案是以您所需的精度指定 double_precision ,但这不允许您有选择地将特定列四舍五入到所需的精度。
另一种选择是在这里去掉中间人 df.to_json ,而是使用 python 的内置 json.dump :

import json

# convert to string
json.dumps(df.to_dict())
# '{"col1": {"0": 11111111.84, "1": 123456.55}, "col2": {"0": 3, "1": 4}}'

# save as a file
json.dump(df.to_dict(), f) # f is an open fileobj
如您所见,这与精度无关。 Standard floating point caveats 仍然适用。

关于python - to_json() 函数错误地导出了带有 float64 的 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62927218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com