[英]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.
而且我们可以很好地控制具体的格式化细节,通过将floatfmt=".3g"
作为参数传递,其操作在这里解释得很清楚:
...确切的规则如下:假设以表示类型“e”和精度 p-1 格式化的结果将具有指数 exp。 然后,如果 m <= exp < p,其中 m 是 -4 表示浮点数,-6 表示小数,则数字的格式为表示类型“f”和精度 p-1-exp。 否则,数字将使用表示类型“e”和精度 p-1 进行格式化。 在这两种情况下,从有效数字中删除无关紧要的尾随零,如果小数点后面没有剩余数字,也会删除小数点,除非使用“#”选项...
除了我不想删除尾随零,而且我看不到一种简单的方法来阻止它们。
如果你想要一个可重现的例子,这里是 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"))
给
| 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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.