I’ve looked thru countless examples, but I cannot figure out how to do the below.
Any tips would be greatly appreciated
Original df (note the multilevel)
Gender A B
sum count sum count
0 M 10 1 50 14
1 F 20 3 5 2
I want to pivot/transpose to this multilevel df:
Gender M F
sum count sum count
0 A 10 1 20 3
1 B 50 14 5 2
I tried all sorts of pivoting, melting, transposing but can’t get this simple result.
You have several options, but you need to stack
/unstack
:
df.droplevel(0).unstack().unstack([2, 1])
Or:
df.droplevel(0).stack(0).unstack(0).swaplevel(axis=1)
Output:
F M F M
sum sum count count
Gender
A 20 10 3 1
B 5 50 2 14