When I create a multi-indexed table in one shot, sortlevel() works as expected. However, if I concatenate multiple tables to create the same multi-indexed table, I cannot sortlevel() anymore. 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 these to produce:
country name
first 0 Albania Jeff
second 1 Zimbabwe Fred
However, I only get that for "working". Anyone knows what I am doing wrong ? Using pandas 0.19.2
Try this ?
working.sort_index()
Out[702]:
country name
first 0 Albania Jeff
second 1 Zimbabwe Fred
or to be more specific
working.sort_index(level=[0, 1], ascending=[True, False])
EDIT: Your multiple index labels show as 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 the not_working
sort work :
not_working.sort_index(level=[0, 1], ascending=[False, False])
Out[567]:
country name
first 0 Albania Jeff
second 1 Zimbabwe Fred
sortlevel() is deprecated so try to use sort_index()
not_working.sort_index(level = 1)
And
working.sort_index(level = 1)
You get
country name
first 0 Albania Jeff
second 1 Zimbabwe Fred
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With