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 do I sort pandas data frame that has a multi-index?

DF I am working with

Hey guys I got that dataframe that you see in the image and I want to sort it by the first ‘всичко‘ column the one under ‘Общо’.

This is the output when I type:

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

df.columns =

MultiIndex([(     '  Общо',  '  всичко'),
            (     '  Общо',   '   мъже'),
            (     '  Общо',  '    жени'),
            ('В градовете',  '  всичко'),
            ('В градовете',     ' мъже'),
            ('В градовете',     ' жени'),
            (   'В селата', '   всичко'),
            (   'В селата',     ' мъже'),
            (   'В селата',     ' жени')],
           names=['Области', 'Общини'])

and

df.index =

Index(['Общо за страната', 'Благоевград', 'Банско', 'Белица', 'Благоевград',
       'Гоце Делчев', 'Гърмен', 'Кресна', 'Петрич', 'Разлог',
       ...
       'Нови пазар', 'Смядово', 'Хитрино', 'Шумен', 'Ямбол', 'Болярово',
       'Елхово', 'Стралджа', 'Тунджа', 'Ямбол'],
      dtype='object', length=294)

Again, I need to the ‘всичко‘ column in descending order.

Best regards.

I tried using the df.sort_values() but I am having difficulties working around the MultiIndex

>Solution :

you can use:

df=df.sort_values([('  Общо',  '  всичко')], ascending=False) #define columns names as a tuple
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