Home > Net >  Reorganize aggregate results in pandas multilevel-columns dataframe
Reorganize aggregate results in pandas multilevel-columns dataframe

Time:04-01

I have a dataframe with 217 rows:

df
        A           C      
       fm    ae    fm    ae
0   0.491 0.368 0.789 0.789
1   0.369 0.333 0.433 0.412
2   0.372 0.276 0.772 0.759
3   0.346 0.300 0.474 0.391
4   0.213 0.161 0.323 0.312
..    ...   ...   ...   ...
212 0.000 0.000 1.000 1.000
213 1.000 1.000 1.000 1.000
214 1.000 1.000 1.000 1.000
215 1.000 1.000 1.000 1.000
216 1.000 1.000 1.000 1.000

[217 rows x 4 columns]

I need to report the mean results, and I get the following results:

df.mean()
A  fm   0.548
   ae   0.508
C  fm   0.671
   ae   0.650
dtype: float64

But I would like the output to look like this:

   fm       ae   
A  0.548    0.508
C  0.671    0.650

I tried with df.mean().groupby(level=0) but the output was none. What is the cleanest way to achieve this organization of aggregate results?

CodePudding user response:

One way is to unstack it:

out = df.mean().unstack()

or you could stack it, then use groupby mean:

out = df.stack(level=0).groupby(level=1).mean()

Output:

       ae      fm
A  0.5438  0.5791
C  0.7663  0.7791
  • Related