The round() Function with a Pandas Series
Let's find out how the round operator works in pandas.
We'll cover the following
Try it yourself
Try executing the code below to see the result.
import pandas as pds = pd.Series([-2.5, -1.5, -0.5, 0.5, 1.5, 2.5])print(s.round())
Explanation
Rounding is easy most of the time. For example, round(1.1)
evaluates to 1
and round(1.8)
evaluates to 2
.
The question is, how do we round the numbers? Should we round up or round down? Turns out, there are a lot of ways to do it.
Python 3 uses bankers’ rounding. In this type of rounding, odd numbers are rounded up, and even numbers are rounded down.
Bankers' Rounding
Number | Rounded Number |
3.5 | 4.0 |
2.5 | 2.0 |
4.2 | 4.0 |
-2.0 | -2.0 |
-3.7 | -4.0 |
2.6 | 3.0 |
The reasoning behind this method is that if we round a list of numbers, the errors will cancel each other out assuming there are roughly the same number of odd and even numbers.
Get hands-on with 1300+ tech skills courses.