How come standard functions like abs or count work on a dataframe?

Question:

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?

Asked By: Jules Olléon

||

Answers:

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__()
Answered By: Barmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.