我将 pandas 数据帧输出到我正在编写的报告中,这很容易,就像您现在可以将df.to_markdown()数据帧转换为 Markdown 表一样,然后 pandoc 可以生成报告。
我们可以通过floatfmt=".3g"作为参数传递来非常精细地控制特定的格式细节,其操作在这里解释得非常清楚:
...精确的规则如下:假设用表示类型“e”和精度 p-1 格式化的结果将具有指数 exp。然后,如果 m <= exp < p,其中 m 为 -4(对于浮点数)和 -6(对于小数),则数字将采用表示类型“f”和精度 p-1-exp 进行格式化。否则,数字将采用表示类型“e”和精度 p-1 进行格式化。在这两种情况下,都会从有效数字中删除无意义的尾随零,并且如果小数点后面没有剩余数字,也会删除小数点,除非使用“#”选项...
除了我不希望删除尾随零,而且我看不到一种简单的方法来防止它们被删除。
如果您想要一个可重现的示例,请看这里:
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"))
Run Code Online (Sandbox Code Playgroud)
给出
| Numbers |
|----------:|
| 0.1 |
| 0.12 |
| 0.1 |
| 0.099 |
| 0.12 |
| 0.012 |
Run Code Online (Sandbox Code Playgroud)
我可以将其更改为指定十进制数字,就像这样
print(df.to_markdown(showindex=False, floatfmt=".2f"))
Run Code Online (Sandbox Code Playgroud)
这使
| Numbers |
|----------:| …Run Code Online (Sandbox Code Playgroud)