Search code examples
pandasroundingbuilt-in

How and why does Python's built-in round() function work flawlessly with pandas?


I have difficulty in understanding the following behavior of Python's built-in "round" function:

Round doesn't work with lists:

round([1.345, 2.718], 2) # Raises TypeError

Round doesn't work with numpy arrays:

import numpy as np
round(np.array([1.345, 2.718]), 2) # Raises TypeError

However, you can use "round" smoothly with pandas as seen below.

Is this some kind of overloading or special handling due to the "courtesy" of pandas?

import pandas as pd
round(pd.Series([1.345, 2.718]), 2) # Works just fine

Solution

  • Pandas Series objects implement the __round__ method, which gets called first in CPython.