Python 熊猫的四舍五入数字
如何将一根柱子四舍五入到1dpPython 熊猫的四舍五入数字,python,python-3.x,pandas,Python,Python 3.x,Pandas,如何将一根柱子四舍五入到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)) 就浮点操作而言,Python的行为与包括C和Java在内的许多流行语言类似。许多易于用十进制表示法书写的数字不能用二进制浮点精确表示。0.95的十进制值实际上是0.94999999996 检查: from decimal imp
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))
就浮点操作而言,Python的行为与包括C和Java在内的许多流行语言类似。许多易于用十进制表示法书写的数字不能用二进制浮点精确表示。0.95的十进制值实际上是
0.94999999996
检查:
from decimal import Decimal
Decimal(0.95)
输出
Decimal('0.9499999999999999555910790149937383830547332763671875')
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
下面是一个有用的“正常”舍入函数,它接受数字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
代码
输出测向
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))
输出
Decimal('0.9499999999999999555910790149937383830547332763671875')
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
也许可以从这里得到一些启发: