Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 17274

pandas: sorting multi-level columns

$
0
0

I have the following pandas dataframe:

import pandas as pddata1 = [['01/01/2000', 101, 201, 301],        ['01/02/2000', 102, 202, 302],        ['01/03/2000', 103, 203, 303],]df1 = pd.DataFrame(data1, columns=['date', 'field1', 'field2', 'field3'])df1 = df1.set_index('date')data2 = [['01/01/2000', 101, 201, 301],        ['01/02/2000', 102, 202, 302],        ['01/03/2000', 103, 203, 303],]df2 = pd.DataFrame(data2, columns=['date', 'field2', 'field1', 'field3'])df2= df2.set_index('date')df = pd.concat([df1, df2], keys={'group1':df1, 'group2': df2 }, axis=1)df

This produces:

            group1                  group2            field1  field2  field3  field2  field1  field3date                        01/01/2000  101     201     301     101     201     30101/02/2000  102     202     302     102     202     30201/03/2000  103     203     303     103     203     303

I would like to sort the group and fields by a custom order. For level 1 of the column, I tried the following:

group_sort=['group2', 'group1']m = {k:v for k, v in enumerate(group_sort)}df = df.sort_index(axis=1, key=lambda x: x.map(m), level=1)df

This produces the following, which is still the same as the original dataframe:

            group1                  group2            field2  field1  field3  field1  field2  field3date                        01/01/2000  101     201     301     101     201     30101/02/2000  102     202     302     102     202     30201/03/2000  103     203     303     103     203     303

For level 0 (the fields) I tried:

field_sort=['field3', 'field2', 'field1']m = {k:v for k, v in enumerate(field_sort)}df = df.sort_index(axis=1, key=lambda x: x.map(m), level=0)df

But this produces:

            group1  group2  group1  group2  group1  group2            field1  field1  field2  field2  field3  field3date                        01/01/2000  201     101     101     201     301     30101/02/2000  202     102     102     202     302     30201/03/2000  203     103     103     203     303     303

So my question is - how would I sort both group and fields?Is there a cleaner, more concise or efficient way of doing this?

What I am expecting as an output sorted as follows:

            group2                  group1            field3  field2  field1  field3  field2  field1date                        01/01/2000  301     201     101     301     201     10101/02/2000  302     202     102     302     202     10201/03/2000  303     203     103     303     203     103

Thanks


Viewing all articles
Browse latest Browse all 17274

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>