I have a multi index table in pandas that is divided by columns, like in the example below:
import pandas as pd
header = pd.MultiIndex.from_product([['loc1','loc2'],
['S1','S2']],
names=['loc','S'])
df = pd.DataFrame(np.random.randint(1, high=5, size=(5,4)),
index=['a','b','c','d','e'],
columns=header)
print(df)
with output:
loc loc1 loc2
S S1 S2 S1 S2
a 4 2 2 5
b 1 4 2 4
c 2 4 2 3
d 3 4 1 2
e 4 1 3 1
I'm trying to perform actions on "loc1" and "loc2", for which I use
df.agg({'loc1':sum, 'loc2':np.mean})
but I'm getting an error: "SpecificationError: nested renamer is not supported".
The expected output is a row with the sum of (loc1, S1) and (loc1, S2), and the mean of (loc2, S1) and (loc2, S2),in my case
loc1 loc2
sum mean
S1 S2 S1 S2
14 15 2 3
How can I do this calculation with the "agg" function? Is there any work around?
p.s. I know I can do it like in the answer Pivot table with multiple aggfunc sum and normalize one column, but it seems somehow "non-pythonic".