为什么熊猫舍入法不能将0.5舍入到1?

时间:2018-10-08 19:11:14

标签: python pandas rounding

我发布的答案是我认为的答案,因为在这里找不到类似的问题答案。

我期望大熊猫round方法将0.5舍入为1。

>>> import pandas as pd
>>> pd.Series([0.5, 1.5, 2.5, 3.5, 4.5]).round()
0    0.0
1    2.0
2    2.0
3    4.0
4    4.0
dtype: float64

更奇怪的是:Python的round方法在Python 2.7和3.6中具有不同的行为:

Python 2.7:

>>> [round(x) for x in [0.5, 1.5, 2.5, 3.5, 4.5]]
[1.0, 2.0, 3.0, 4.0, 5.0]

Python 3.6:

>>> [round(x) for x in [0.5, 1.5, 2.5, 3.5, 4.5]]
[0, 2, 2, 4, 4]

这与浮点表示或我的平台(Mac OS X)有关吗?

2 个答案:

答案 0 :(得分:2)

我相信这种情况实际上是python中预期的行为,而不是浮点问题。看着documentation

  

如果两个倍数相等接近,则将舍入为偶数选择(例如,round(0.5)和round(-0.5)均为0,round(1.5)均为2)

答案 1 :(得分:0)

这确实是由于{3} {3}中描述的floating point arithmetic所致:

  

round()对于浮点的行为可能令人惊讶:例如,round(2.675, 2)给出2.67而不是预期的2.68。这不是错误:这是由于大多数小数部分不能完全以浮点数表示的结果。

相关问题