Home > front end >  How come standard functions like abs or count work on a dataframe?
How come standard functions like abs or count work on a dataframe?

Time:12-09

I realized that for some standard python functions like round or abs, instead of invoking them as a method on a dataframe like:

df['MyCol'].round()
df['MyCol'].abs()

or using apply like:

df['MyCol'].apply(round)
df['MyCol'].apply(abs)

I can also call their std library equivalent directly for the same result:

round(df['MyCol'])
abs(df['MyCol'])

How come this works? Is there something in the round and abs implementations that allows to extend them to new types somehow?

CodePudding user response:

Many Python built-in functions are designed to be extended by classes, so they'll call a dunder method if it exists.

From the documentation of round():

For a general Python object number, round delegates to number.__round__.

So when you call round(df['MyCol']) it's equivalent to

df['MyCol'].__round__()
  • Related