pythonpandasrounding

Why does Pandas round method not round 0.5 up to 1?


I expected pandas round method to round 0.5 up to 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

Even more strange: Python's round method has different behaviour in Python 2.7 and 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]

Is this something to do with floating-point representation or my platform (Mac OS X)?


I'm posting this with what I think is the answer because I couldn't find a similar question-answer here.


Solution

  • I believe in this case it is actually the intended behaviour in Python, and not a floating point problem. Looking at the documentation:

    if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2)