Sort Pandas MultiIndex that contains str and tuples

Viewed 131

So I have a dataframe with multilevel multiindex where the smaller index is parent and adding a level of index creates the childern that looks something like

(a,foo,1)
(a,foo,2)
(a,foo)
a        
(b, foo,1)
(b, bar,1)
(b, foo)
(b, bar)
b 

and I want to sort the index but when using the sort_index function I receive the following error, TypeError: '<' not supported between instances of 'str' and 'tuple'

Since any index greater than 1 level is stored as a tuple and the single indexes are stored as strings I cannot sort the index.

What is the best approach to have my index become a single datatype so I can sort it?

a
(a,foo)
(a,foo,1)
(a,foo,2)
b        
(b, bar)
(b, bar,1)
(b, foo)
(b, foo,1)




 
1 Answers

Let us try explode in row then sort_values with na_position

l = df.index
s = pd.DataFrame(l).sort_values([0,1,2],na_position='first').index
df = df.iloc[s]
Related