PYTHON: pandas to_csv is rounding, any way for it to not round?

huangapple go评论61阅读模式
英文:

PYTHON: pandas to_csv is rounding, any way for it to not round?

问题

我正在尝试将数据框中的值保存到CSV文件中。然而,pandas在保存时进行了太多的四舍五入,导致我的数字出现了很大的偏差。
例如,像0.00002134566这样的值会被四舍五入为0.0:

df = pd.read_csv(file_path, float_precision='round_trip')

df['addCol1'] = 0.0005

df.to_csv("output_path", index=False, header=False)

是否有任何方法可以告诉pandas不要对数字进行四舍五入?

英文:

I am trying to save values in a dataframe to a csv file. However, pandas to csv is rounding so much that my numbers are really off.
For example, values like 0.00002134566 would be rounded to a 0.0:

df = pd.read_csv(file_path, float_precision='round_trip')

df['addCol1'] = 0.0005

df.to_csv(f"output_path", index=False, header=False)

Is there any way to tell pandas not to round the numbers?

答案1

得分: 1

将这行代码更改为:

df.to_csv(f"output_path", index=False, header=False, float_format='%.11f')

这将保留浮点值的小数部分,最多保留11位小数。

英文:

Change this line

df.to_csv(f"output_path", index=False, header=False)

to this.

df.to_csv(f"output_path", index=False, header=False, float_format='%.11f')

It'll keep float values up to 11 decimal places.

huangapple
  • 本文由 发表于 2023年6月30日 05:17:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76584654.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定