Consider a dataframe:
df = pd.DataFrame(
{'last_year': [1, 2, 3], 'next_year': [4, 5, 6]},
index=['foo', 'bar', 'star']
)
last_year next_year
foo 1 4
bar 2 5
star 3 6
I am looking for an easy way to display totals around this table, both column and row wise.
My thought was to throw it through .pivot_table()
:
pd.pivot_table(
df,
index=df.index,
margins=True,
aggfunc=sum
)
However, this only works for the first axis (vertically):
last_year next_year
bar 2 5
foo 1 4
star 3 6
All 6 15
What did I miss? How come no row wise totals are calculated as well, just like in this documentation's example? Also, why is it messing up my index' order?
I'm not interested in df['All'] = df.sum(axis=1)
kind of solutions; I want a dynamic approach which does not affect my original dataframe. A pivot table seems like the most logical way to do this (as far as I know) but maybe there are better ways!