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

How to groupby multindexed columns with Pandas while keeping the column structure?

I have a dataframe with multiindexed columns I would like to group by level 0 AND 1. Duplicated columns have values I would like to sum. How can I groupby without dropping the other level ? This is what I have tried but it removes one of the level.

Level 0 is dropped.

data.groupby(level=1, axis=1).sum()
Index(['last', 'quoteVolume'], dtype='object')

Level 1 is dropped.

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

data.groupby(level=0, axis=1).sum()
Index(['ACA', 'DOT', 'KSM', 'MOVR'], dtype='object')

The columns:

MultiIndex([(       'last',  'DOT'),
            ('quoteVolume',  'DOT'),
            (       'last',  'DOT'),
            ('quoteVolume',  'DOT'),
            (       'last',  'KSM'),
            ('quoteVolume',  'KSM'),
            (       'last',  'KSM'),
            ('quoteVolume',  'KSM'),
            (       'last', 'MOVR'),
            ('quoteVolume', 'MOVR'),
            (       'last', 'MOVR'),
            ('quoteVolume', 'MOVR'),
            (       'last',  'ACA'),
            ('quoteVolume',  'ACA')],
           )

How can I do that ?

The expected output is:

MultiIndex([(       'last',  'DOT'),
            ('quoteVolume',  'DOT'),
            (       'last',  'KSM'),
            ('quoteVolume',  'KSM'),
            (       'last', 'MOVR'),
            ('quoteVolume', 'MOVR'),
            (       'last',  'ACA'),
            ('quoteVolume',  'ACA')],
           )

>Solution :

you can use this, use the same groupby and set columns later using pd.MultiIndex.from_tuples

out = df.groupby(df.columns,axis=1).sum()
out.columns = pd.MultiIndex.from_tuples(out.columns)

print(out)
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