如何将一列四舍五入到 1dp?
df value
0 0.345
1 0.45
2 0.95
预期输出
0.3
0.5
1.0
以下都给出了错误的答案:
df.value.round(1)
df.value.apply(lambda x:round(x,1))
答案 0 :(得分:1)
就浮点运算而言,Python 的行为类似于许多流行语言,包括 C 和 Java。许多可以轻松用十进制表示法书写的数字无法用二进制浮点数精确表示。 0.95 的十进制值实际上是 0.94999999999999996
检查:
from decimal import Decimal
Decimal(0.95)
输出
Decimal('0.9499999999999999555910790149937383830547332763671875')
这是一个有用的“普通”舍入函数,它接受数字 n,并将 n 返回到指定的小数位:
import math
def normal_round(n, decimal):
exp = n * 10 ** decimal
if abs(exp) - abs(math.floor(exp)) < 0.5:
return math.floor(exp) / 10 ** decimal
return math.ceil(exp) / 10 ** decimal
原始df
df = pd.DataFrame({'value': [0.345, 0.45, 0.95]})
value
0 0.345
1 0.450
2 0.950
代码
df['value'] = df['value'].apply(lambda x: normal_round(x, 1))
输出df
value
0 0.3
1 0.5
2 1.0
有关舍入浮点数的更多示例:
df = pd.DataFrame({'value': [0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95]})
df['value_round'] = df['value'].apply(lambda x: round(x, 1))
df['value_normal_round'] = df['value'].apply(lambda x: normal_round(x, 1))
输出
value value_round value_normal_round
0 0.15 0.1 0.2
1 0.25 0.2 0.3
2 0.35 0.3 0.4
3 0.45 0.5 0.5
4 0.55 0.6 0.6
5 0.65 0.7 0.7
6 0.75 0.8 0.8
7 0.85 0.8 0.9
8 0.95 0.9 1.0