I have a dataframe looking like that :
2023-12-31 2024-01-31
myvalue1 myvalue2 myvalue1 myvalue2
a 2 6 2 6
b 3 7 3 7
c 4 8 4 8
which can be created by :
df = pd.DataFrame(index=['a', 'b', 'c'], data=
{'myvalue1':[2,3, 4], 'myvalue2':[6,7,8]})\
.reindex(['myvalue1', 'myvalue2'] * 2, axis=1) \
.set_axis(pd.MultiIndex.from_product([['2023-12-31','2024-01-31'], ['myvalue1', 'myvalue2']]), axis=1)
How can I get the sum in each column in the following format :
myvalue1 myvalue2
2023-12-31 9 21
2024-01-31 9 21
Note that this is only the example where pair of columns are the same.
Thank you
sum the rows and reshape with unstack:
out = df.sum().unstack()
Output:
myvalue1 myvalue2
2023-12-31 9 21
2024-01-31 9 21
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With