pythonpandasroundingbuilt-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.

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

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


Solution

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