简体   繁体   中英

How to order Pandas multiIndex items in non lexicographical order

Let's say I have this multiIndex


                                  Price
Fruit     Season     Location     

Apple     Winter     Japan          8
                     Other          5
                     China          8
Melon     Any        Africa         7
                     Other          2
                     Colombia       4

How can I arrange the items in Location so that 'Other' will always be the last regardless of alphabetical order of other items? I appreciate any help.

Use:

print (df)
                       Price
Fruit Season Location       
Apple Winter Singapur      8
             Other         5
             China         8
Melon Any    Africa        7
             Other         2
             Colombia      4

You can create ordered CategoricalIndex for second level, then use MultiIndex.set_levels , so possible use DataFrame.sort_index

i = df.index.levels[2]
out = sorted(i.difference(['Other']))
out.append('Other')
print (out)
['Africa', 'China', 'Colombia', 'Singapur', 'Other']

df.index = df.index.set_levels(pd.CategoricalIndex(i, ordered=True, categories=out),level=2)

df = df.sort_index()
print (df)
                       Price
Fruit Season Location       
Apple Winter China         8
             Singapur      8
             Other         5
Melon Any    Africa        7
             Colombia      4
             Other         2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM