简体   繁体   中英

Printing number formatting in excel file from python

I have multiple columns of negetive numbers, integers. Some of them has to be in a specific format.

Ex: Input dataframe:

Value1 Value2 Value2
1 -5 -50.5
2 35.6 -70
-4 3 -20

expected output is

Value1 Value2 Value2
1 (5) (50.5)
2 35.6 (70)
-4 3 (20)

As you can see only Value2 and Value3 columns have negative values which are displayed in parenthesis.

Now i have tried the below to display the required format and its working fine:

formatter = lambda x: '(%s)' % str(x)[1:] if x < 0 else str(x)
pd.options.display.float_format = formatter
df6.head()

but when i use the below to print it in excel file It does not follow the required format.

df6.to_excel('output.xlsx', index=False)
print('Spreadsheet saved.')

I need a way to print this properly in excel output file

使用DataFrame.applymap

df6.applymap(formatter).to_excel('output.xlsx', index=False)

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