Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parenthesis on .upper() and .apply(str.upper)

Tags:

python

pandas

Why do upper in df.apply(df.str.upper) doesn't require a parenthesis, but upper() method requires them as in df.str.upper()?

Is there some concept I've miss?

like image 640
Claude Avatar asked May 14 '26 16:05

Claude


2 Answers

The () means "call this function now".

print(str.upper())

Referring to a function without the () does not call the function immediately.

map(str.upper)

The str.upper function is passed to the map function. The map function can now decide what it does with the str.upper function. It might call it once, or multiple times, or store it somewhere for later use.

like image 108
Roland Illig Avatar answered May 16 '26 05:05

Roland Illig


When you use .apply(function_name), the internals treats function_name as a reference to the function that has been applied. Hence, only the function name is passed and that too without parentheses.
When it is applied to the entity, it will be accessed from the function_name.
Its just like passing a function as an argument to another function.

Example:

def fun(x):
   return x*x

def fun_b(function):
   return function(3)

print(fun_b(fun))
like image 36
taurus05 Avatar answered May 16 '26 06:05

taurus05



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!