I have a dataframe that I converted to a pivot table using pd.pivot_table method and a sum aggregate function:
summary = pd.pivot_table(df,
index=["Region"],
columns=["Product"],
values=['Price'],
aggfunc=[np.sum],
fill_value=0,
margins=True,
margins_name="Total"
)
I have received an output like this:
I would like to add another pivot table that displays percent of grand total calculated in the previous pivot table for each of the categories. All these should add up to 100% and should look like this.
I have tried the following workaround that I found on stackoverflow:
total = df['Price'].sum()
table = pd.pivot_table(DF,
index=["Region"],
columns=["Product"],
values=['Price'],
aggfunc=[np.sum,
(lambda x: sum(x)/total*100)
],
fill_value=0,
margins=True,
margins_name="Total"
)
This calculated the percentages but they only add up to 85%...
It'd be great to not have to calculate the total outside of the pivot tabe and just be able to call the Grand Total from the first pivot. But even if I have to calculate separately, like in the code above, as long as it adds up to 100% it would still be great.
Thank you in advance!