Pandas how to calculate mean for second level multi index columns
Question:
In Pandas, How to get mean for second level columns?
bar baz foo
one two one two one two
aaa 1 2 3 4 5 6
bbb -1 -2 -3 -4 -5 -6
Expected:
one two
aaa 3 4
bbb -3 -4
Answers:
Use parameters level=1
and axis=1
for MultiIndex in columns:
df = df.groupby(level=1, axis=1).mean()
In Pandas, How to get mean for second level columns?
bar baz foo
one two one two one two
aaa 1 2 3 4 5 6
bbb -1 -2 -3 -4 -5 -6
Expected:
one two
aaa 3 4
bbb -3 -4
Use parameters level=1
and axis=1
for MultiIndex in columns:
df = df.groupby(level=1, axis=1).mean()