Pandas 处理非常小的数字的舍入

Pandas handling rounding with very small number

我有一个如下所示的数据框。我正在尝试将数字四舍五入为小数点后一位。但在某些情况下,如果一个数字是 0.9 或以下,我需要以最不精确的四舍五入显示数字

import pandas as pd
df_input = pd.read_csv('test.csv')
print(df_input)

数据框的结果,

     Cateogry  Consumption
0  Category 1    31.248175
1  Category 1     0.401825
2  Category 2     0.178149
3  Category 2     6.538878
4  Category 3     0.011308
5  Category 3     0.023273
6  Category 4     0.000533
7  Category 5     0.126154

我将上面的数据框汇总如下,

print(df_input.round(1))

     Cateogry  Consumption
0  Category 1         31.2
1  Category 1          0.4
2  Category 2          0.2
3  Category 2          6.5
4  Category 3          0.0   // It should show 0.01
5  Category 3          0.0   // It should show 0.02
6  Category 4          0.0   // It should show 0.0005
7  Category 5          0.1

就像我在第 4、5、6 行中评论的那样,它应该按照我显示的方式显示值。

有什么办法可以做到吗?

如果您只想对数字进行四舍五入,这应该可以正常工作:

from math import floor, log10
df_input["Consumption"] = df_input["Consumption"].apply(lambda x: round(x, max(1, - int(floor(log10(abs(x)))))))
df_input["Consumption"]
#0    31.2000
#1     0.4000
#2     0.2000
#3     6.5000
#4     0.0100
#5     0.0200
#6     0.0005
#7     0.1000

您可以通过格式化处理尾随零,fe:

format_mapping = {"Consumption": "{:,g}"}
df_input.style.format(format_mapping)
#   Cateogry    Consumption
#0  Category 1  31.2
#1  Category 1  0.4
#2  Category 2  0.2
#3  Category 2  6.5
#4  Category 3  0.01
#5  Category 3  0.02
#6  Category 4  0.0005
#7  Category 5  0.1