Nicole Ardizzi
Nicole Ardizzi

Reputation: 61

Python - Calculating Percent of Column Total in Pivot Tables

The following code gives me the percentage of

df_percentage = np.round(df*100/df.iloc[-1,-1], 1)
df_percentage.tail(5)

But this gives me the percent of grand total: percentage of grand total

I would like to get another pivot table that displays values as a percentage of column total like this:

percentage of column

Upvotes: 1

Views: 467

Answers (2)

Nicole Ardizzi
Nicole Ardizzi

Reputation: 61

JK Chai's answer would have been correct if the df did not include the total sum of each row and column (this was calculated using margins=True in the pivot_table function). I was able to resolve using the following code:

df_percentage = np.round(df*100/df.iloc[-1], 1)

Upvotes: 0

JK Chai
JK Chai

Reputation: 145

You should be able to compute each column percentage by summing row-wise and divide each data based on that corresponding column "sum".

Try this:

np.round((df/df.sum(axis=0))*100,1)

Upvotes: 0

Related Questions