Reputation: 21
I have a dataframe with several columns with numbers. I'd like to export them as integers but with comma separators for numbers over 999.
I was able to do it, but when they are exported I'm not able to manipulate the numbers, as if they turn to strings because of the comma.
I tried this with no luck:
format_mapping={'Balance': '{:,.0f}'}
for key, value in format_mapping.items():
cash_tracker_df[key] = cash_tracker_df[key].apply(value.format)
I read the following to get where I'm at:
Python Pandas Apply Formatting to Each Column in Dataframe Using a Dict Mapping
https://xlsxwriter.readthedocs.io/tutorial02.html
I used pandas and xlsxwriter.
Any help would be appreciated.
Upvotes: 2
Views: 3318
Reputation: 1393
You should use the num_format property when you are defining the format.
import pandas as pd
df = pd.DataFrame({'A': [1,2,3,4,1000,1001,10000,10001]})
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
cellFormat = workbook.add_format({'num_format': '#,##'})
worksheet.set_column('A:A', 10, cellFormat)
writer.save()
Output:
Finally if you want to use a decimal separator as well you should use
'num_format': '#,##.00'
For more info have a look here
Upvotes: 4