简体   繁体   English

从python打印excel文件中的数字格式

[英]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.如您所见,只有 Value2 和 Value3 列具有显示在括号中的负值。

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.但是当我使用下面的在 excel 文件中打印它时,它不遵循所需的格式。

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

I need a way to print this properly in excel output file我需要一种在 excel 输出文件中正确打印的方法

使用DataFrame.applymap

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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