Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue while displaying trailing zeroes in Excel with StyleFrame library in Python

While using the StyleFrame library to write into an excel file, I am not able to retain 3 decimal digits if there are trailing zeroes.

For example, consider the following dataframe:

dataframe df with two columns, "Security Name" and "MGEAFE %Port"

Next, I write this dataframe into a StyleFrame object for data formatting and finally, write the StyleFrame object into an excel file:

sf = StyleFrame(df)
sf = sf.apply_headers_style(...)
sf = sf.apply_column_style(...)
sf.to_excel(writer, float_format="%.3f")

Here's my output:

output

What I would like to do is, show 0.08 as 0.080 as my float format suggests "%.3f" in the to_excel() call.

Any suggestions please?

like image 997
viks_python Avatar asked Oct 17 '25 01:10

viks_python


1 Answers

Well, since df.to_excel(writer, float_format='%.3f') does not provide the expected output, sf.to_excel(writer, float_format="%.3f") would not either (StyleFrame.to_excel passes kwargs that it does not recognize to pandas.DataFrame.to_excel).

You can get it to work by using a custom number_format when styling the column. Pass number_format='0.000' ('0.000' is the cell format that Excel uses to denote 3 decimal places) to the Styler object that you use to style the MGEAFE %port column.

from StyleFrame import StyleFrame, Styler


df = pd.DataFrame({'a': [0.021, 0.029, 0.080]})
StyleFrame(df, Styler(number_format='0.000')).to_excel('test.xlsx').save()

enter image description here

like image 175
DeepSpace Avatar answered Oct 18 '25 23:10

DeepSpace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!