1

I have a dataframe which have float numbers and I would like to save it with the same number of digits. This is my dataframe df:

       1     0.917007  0.920562  0.922801  0.922745  0.917396  0.922445   
       2     0.914374  0.926690  0.914257  0.914607  0.914462  0.910307   
       3     0.919565  0.907405  0.916554  0.916463  0.919817  0.917184   
       4     0.912238  0.915469  0.900786  0.900752  0.912059  0.919894   
       5     0.906972  0.920995  0.918015  0.918200  0.908895  0.907092 

And I am saving it doing:

from pandas import ExcelWriter
writer = ExcelWriter('PythonExport.xlsx')
table.to_excel(writer,'aName',float_format='%11.4f')
writer.save()

But when I open the file, I see this:

enter image description here

How can I do to force the number of digits saved for each cell to get this?:

enter image description here

Edit: same happening trying to save as a csv file with the following

table.to_csv('PythonExport.csv', sep=',',float_format='%11.4f')

Note: I'm using python3

diens
  • 639
  • 8
  • 26

2 Answers2

2

The following should work as described here

df.applymap('{:.4f}'.format).to_csv('PythonExport.csv')

To verify make sure you open the .csv in a text editor and not Excel.

jeschwar
  • 1,286
  • 7
  • 10
  • I'm using LibreOffice Calc to open it and the .csv file is not right showed in that program but yes in a text editor, as you said. But I've also tried doing `table.applymap('{:.4f}'.format).to_excel(w...` and it works even opening it with the LibreOffice Calc. Thanks a lot! – diens Nov 30 '18 at 21:04
  • 1
    No problem. Check that your columns are indeed floats by checking the output of `df.dtypes` before doing the float formatting. – jeschwar Nov 30 '18 at 21:21
1

You need to create format and then add it to column wherever you need to add, this might help you.

df.to_excel(writer, sheet_name='Sheet1')
workbook  = writer.book
worksheet = writer.sheets['Sheet1']
format1 = workbook.add_format({'num_format': '0.0000'})
worksheet.set_column('B:B', None, format1)
writer.save()

More info: http://xlsxwriter.readthedocs.io/example_pandas_column_formats.html

Sarang
  • 126
  • 7