How to sort Pandas DataFrame both by MultiIndex and by value?
IIUC:
In [29]: test.sort_values('sum', ascending=False).sort_index(level=0)
Out[29]:
sum count
src dst
1 2 80 2
5 10 1
2 8 80 1
UPDATE: very similar to @anonyXmous's solution:
In [47]: (test.reset_index()
.sort_values(['src','sum'], ascending=[1,0])
.set_index(['src','dst']))
Out[47]:
sum count
src dst
1 2 70 2
5 10 1
2 8 90 2
5 65 1
In case anyone else comes across this using google as well. Since pandas version 0.23, you can pass the name of the level as an argument to sort_values
:
test.sort_values(['src','sum'], ascending=[1,0])
Result:
sum count
src dst
1 2 70 2
5 10 1
2 8 90 2
5 65 1