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:
CodePudding user response:
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)
CodePudding user response:
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)