简体   繁体   中英

How to preserve trailing zeros?

I'm outputting a pandas dataframe to a report I'm writing, which is easy as you can now do df.to_markdown() to convert the dataframe to a markdown table, and then pandoc can generate the report.

And we can control the specific formatting details quite finely, by passing floatfmt=".3g" as a parameter, the operation of which is explained very clearly here :

... The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then, if m <= exp < p, where m is -4 for floats and -6 for Decimals, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it, unless the '#' option is used...

Except I do not want trailing zeros to be removed, and I can't see a simple way to prevent them being.

If you want a reproducible example , here you go:

import pandas as pd

df = pd.DataFrame({'Numbers':[0.100, 0.123, 0.101, 0.099, 0.120, 0.012]})
print(df.to_markdown(showindex=False, floatfmt=".2g"))

gives

|   Numbers |
|----------:|
|     0.1   |
|     0.12  |
|     0.1   |
|     0.099 |
|     0.12  |
|     0.012 |

I could change it to specify decimal figures, like so

print(df.to_markdown(showindex=False, floatfmt=".2f"))

which gives

|   Numbers |
|----------:|
|     0.10  |
|     0.12  |
|     0.10  |
|     0.10  |
|     0.12  |
|     0.01  |

--but that's not what I want . I want two significant figures. With trailing zeros. Like this:

|   Numbers |
|----------:|
|     0.10  |
|     0.12  |
|     0.10  |
|     0.099 |
|     0.12  |
|     0.012 |

In order to keep the significant trailing zeros use # .

So change

floatfmt=".2g"

to

floatfmt="#.2g"

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