# Difference while using apply method and vector method

Your Code: I need to understand why these two codes are giving a different result
code 1

``````def percentages(col):
div = col/happiness2015['Happiness Score']
return round(div*100,2)

melt['Percentage']=melt[['value']].apply(percentages)
``````

Code 2
`melt['Percentage']=round(melt['value']/melt['Happiness Score']*100,2)`

What I expected to happen:

I was expecting both of them to give same result but code1 is giving NaN for many rows

Other details:
DF details
main_cols = [‘Country’, ‘Region’, ‘Happiness Rank’, ‘Happiness Score’]
factors = [‘Economy’, ‘Family’, ‘Health’, ‘Freedom’, ‘Trust’, ‘Generosity’, ‘Dystopia Residual’]

melt = pd.melt(happiness2015,id_vars= main_cols, value_vars= factors)

Welcome to our Dataquest Community.

Code 1-
Two mistakes in it.

First, You are dividing a single value from `value` with the whole column `Happiness Score` or all values from the ‘Happiness Score’ column one by one. But you need only one value from it with the corresponding index.

Second, You need to assign the `axis` parameter in the method `apply` to understand how values to send either row or column-wise. By default `axis=0` i.e. row-wise.

Corrected Code 1-

``````def percentages(row):
value=row['value']
score=row['Happiness Score']
div = value/score
return round(div*100,2)

melt['Percentage']=melt.apply(percentages, axis=1)
``````

I have edited it.

Code 2-
It looks correct, for better understanding you can add brackets.

``````melt["Percentage"] = round(((melt["value"]/melt["Happiness Score"]) * 100), 2)
``````

I hope this helps .

2 Likes

use div = col/melt[‘Happiness Score’]
instead of using “div = col/happiness2015[‘Happiness Score’]”

That’s works fine

Hello, what is the value column? The instructions say to convert it to a percentage but there is no value column in the happiness2015 dataframe, as far as I can tell.

Please, read the working of `pd.melt()` function and the slides again carefully. You will find your answer.

1 Like