Pandas sorting MultiIndex after concatenation

When I create a table with multiple indexes in a single snapshot, sortlevel () works as expected. However, if I concatenate multiple tables to create the same table with multiple indexes, I can no longer sort (). Full example below:

import pandas as pd
a=pd.DataFrame({'country':'Zimbabwe','name':'Fred'}, index=[1])
b=pd.DataFrame({'country':'Albania','name':'Jeff'}, index=[0])
not_working = pd.concat([a,b],keys=['second','first'])
working = pd.DataFrame({'country':['Zimbabwe','Albania'],'name':['Fred','Jeff']}, index=pd.MultiIndex.from_tuples([('second',1),('first',0)]))

not_working_sorted = not_working.sortlevel(0)
working_sorted = working.sortlevel(0)

I expect both of them to create:

           country  name
first  0   Albania  Jeff
second 1  Zimbabwe  Fred

However, I only get it for "work." Does anyone know what I'm doing wrong? Using pandas 0.19.2

+6
source share
2 answers

Give it a try

working.sort_index()
Out[702]: 
           country  name
first  0   Albania  Jeff
second 1  Zimbabwe  Fred

or more specifically

working.sort_index(level=[0, 1], ascending=[True, False])

EDIT. Your labels with multiple indexes are shown below.

not_working.index
Out[565]: 
MultiIndex(levels=[['second', 'first'], [0, 1]],
           labels=[[0, 1], [1, 0]])
working.index
Out[566]: 
MultiIndex(levels=[['first', 'second'], [0, 1]],
           labels=[[1, 0], [1, 0]])

So, if you want to sort not_working:

not_working.sort_index(level=[0, 1], ascending=[False, False])
Out[567]: 
           country  name
first  0   Albania  Jeff
second 1  Zimbabwe  Fred
+4
source

sortlevel() , sort_index()

not_working.sort_index(level = 1)

working.sort_index(level = 1)

            country     name
first   0   Albania     Jeff
second  1   Zimbabwe    Fred
+3

All Articles