I created a function percentage to run through for each “Percentage” column but its giving me a huge error
In the function you’ve defined, you’re trying to divide value by the entire melt[“Happiness Score”] column. That might be causing the problem.
It is hard to tell which of the exercises in
Transforming Data with Pandas you are referring to. Is it
slide 7 or 8?
I think it’s slide 7. They’re probably trying to solve this the same way in slide 6. That’s not how I solved it, though, as I see.
Okay. I thought so too. Just to be sure.
I’m referring to slide 7. However, didn’t they do that in the example on Slide 6?
- Using the apply(percentage) function to dividing the value in each row of melt[“value”] by melt[“Happiness Score”], then multiplying it by 100!
Code in slide 6:
- Using the apply(percentages) function to divide the value of each row in the factors columns list by happiness2015[“Happiness Score”]
factors = [‘Economy’, ‘Family’, ‘Health’, ‘Freedom’, ‘Trust’, ‘Generosity’, ‘Dystopia Residual’]
div = col/happiness2015[‘Happiness Score’]
return div * 100
factor_percentages = happiness2015[factors].apply(percentages)
You should select
value column as
Series so use
melt[["value"]] instead of
melt["Percentage"] = melt[["value"]].apply(percentage)
You can see different between both by printing its type.
print(type(melt[["value"]])) # melt[["value"]] will returns DataFrame
print(type(melt["value"])) # melt["value"] will returns Series
.apply function on
DataFrame object implement function
column wise see docs while on
Series object implement function
row wise see docs.