简体   繁体   中英

How to export Python dataframe columns with number as integers with comma separators, and be able to sum/divide/multiply them?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM