0

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?

pillow
  • 23
  • 4
  • Hello! Could you add your code? – Jino Michel Aque Jun 29 '23 at 21:20
  • 1
    This doesn't seem right. [this question](https://stackoverflow.com/questions/12877189/float64-with-pandas-to-csv) has the exact opposite problem -- it's using too many significant digits. – Barmar Jun 29 '23 at 21:21
  • 1
    But the solution should be the same: use the `float_format` argument – Barmar Jun 29 '23 at 21:22
  • Try open your file with txt – BENY Jun 29 '23 at 21:28
  • ahh sorry I just added the code now @JinoMichelAque – pillow Jun 29 '23 at 21:28
  • Why are you using the float_precision='round_trip'? Have you tried it with the default? Also typically a toy example or reproducible example is useful. The example code supplied does not provide something that I can try to reproduce on my end. If you could provide some of the data or toy data that produces the error you are seeing then that would be sufficient. – TPack Jun 29 '23 at 21:35
  • @TPack I was searching Stack Overflow to see if someone had a similar issue, and adding float_precision='round_trip' seemed to fix their code. But you are right, I did not need to use float_precision. float_format for to_csv worked perfectly – pillow Jun 30 '23 at 13:56
  • @pillow if it worked could you please hit the up arrow next to my comment? – TPack Jun 30 '23 at 15:50

1 Answers1

1

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.

Zero
  • 1,807
  • 1
  • 6
  • 17