Skip to content

Instantly share code, notes, and snippets.

@bhavaniravi
Created July 11, 2018 11:08
Show Gist options
  • Save bhavaniravi/902a933b443bd37479ef242d8fec0859 to your computer and use it in GitHub Desktop.
Save bhavaniravi/902a933b443bd37479ef242d8fec0859 to your computer and use it in GitHub Desktop.
Script to calculate pandas subtotal
table = pd.pivot_table(df, values='Quantity', index =['Country','Region'], columns=["Year","Requester"], aggfunc=[np.sum])
result_df = table
for i in range(2):
df2 = table.groupby(level=i).sum()
if i==0:
tot_sum = df2.sum(axis=i)
df2 = pd.concat([df2,pd.DataFrame([tot_sum]).rename({0:"Grand"})]).sort_index(level=[0])
df2.index = pd.MultiIndex.from_arrays([df2.index.values + '_Total',
len(df2.index) * [''],
len(df2.index) * ['']])
result_df = pd.concat([result_df, df2]).sort_index(level=[0])
for i in range(1,3):
df2 = result_df.sum(level=i, axis=1)
df2.columns = pd.MultiIndex.from_arrays([df2.columns.map(str).values + 'Total',
len(df2.columns) * [''],
len(df2.columns) * ['']])
#result_df.insert(loc=i,value=df2)
result_df = pd.concat([result_df, df2], axis=1)
result_df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment