pandasdataframeexport-to-excel

pandas to_excel export numerically inacurrate


I have a Pandas DataFrame that I want to export to Excel.

When doing so using pd.to_excel(...) my floats are getting slightly faulty.

Something like:

df = [0.019,2.117,9.999]

excel = [0.018999901104,2.11700000111,9.999997711454]

All I want is that the Excel valuer are the same as the original values in the df.

Maybe there is a way to do this?

Thank you


Solution

  • In my case I couldn't replicate the same error as yours. Recall to add a minimal reproducible example when possible.

    Nonetheless, the float_format should handle your case

    import pandas as pd
    
    df = pd.DataFrame([0.019, 2.117, 9.999], columns=['values'])
    
    float_format = '%.3f'  
    df.to_excel('output.xlsx', float_format=float_format, index=False)
    

    Result in Excel:

    enter image description here