Apply and Map function without parameters

Screen Link:

My Code:

factors = ['Economy', 'Family', 'Health', 'Freedom', 'Trust', 'Generosity', 'Dystopia Residual']
def percentages(col):
    div=col/happiness2015['Happiness Score']
    return div*100

How that function works properly without us defining any parameter? For example apply.(percentages(factor)).

Hi ! @mr.fuadak
Good question.
.apply() is a method which can be used on column (or group of columns) or rows and it take function as an argument without parentheses and without passing any argument to function itself.
So, what is happening here is when you use the percentages function as a argument to apply() method, by default percentages function taking argument (which is name of column) from below section of code, where you have mentioned on which columns apply() method should apply created function(percentages).

In short, when you call a function without an apply() method then you have to pass the arguments but when you call function with apply() method then you don’t pass argument in function itself, we apply that function on a particular column or row with apply() method. That’s what you did in the code below, you first mentioned the columns (happiness2015[factors]) and then you chained it with the .apply() method having percentages as an argument.

Hope this explains your question below.

Happy Learning!

1 Like

thank you it is more clear now, in other words it is equal to this expression:
percentages (happiness2015[factors])
I hope got it right.

1 Like

I am glad that you found the answer helpful,

Yes, logically it’s true but while writing code

This is how you achieve it with `apply() function.

for name in factors:

this is how you achieve with the loop.

Happy Learning!