Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reorganize aggregate results in pandas multilevel-columns dataframe

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading