如何保留尾随零?

How to preserve trailing zeros?

我正在将 pandas 数据帧输出到我正在编写的报告中,这很容易,因为您现在可以 df.to_markdown() 将数据帧转换为降价 table,然后 pandoc 可以生成报告。

并且我们可以非常精细地控制具体的格式化细节,通过将floatfmt=".3g"作为参数传递,其操作解释得非常清楚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...

除非我不想删除尾随零,而且我看不到防止它们出现的简单方法。

如果你想要一个可重现的例子,给你:

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"))

给予

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

我可以将其更改为指定十进制数字,就像这样

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

这给出了

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

--但是这不是我想要的。我想要两个有效数字。带有尾随零。像这样:

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

为了保留重要的尾随零,请使用 #

所以改变

floatfmt=".2g"

floatfmt="#.2g"