简体   繁体   中英

Pandas - How to sort_values by 2 different columns using 2 different keys

Pandas 1.1.0 added the key paramater to sort_values .

Is it possible to sort by 2 different columns, and use a different key for each?

If not - what would be the best way to achieve this same behavior?

After your first sort_values

df.groupby('col1').apply(lambda x: x.sort_values('col2',ascending=False)).reset_index(level=0, drop=True)

Yes it is doable! the trick is to have the key containing all values used in the sort

here is an example:

def make_sorter(l):
    sort_order = {k:v for k,v in zip(l, range(len(l)))}
    return lambda s: s.map(lambda x: sort_order[x])

a = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
b = ['Windows', 'Android', 'iPhone', 'Macintosh', 'iPad', 'ChromeOS', 'Linux']
df.sort_values(by=['days','device'], key=make_sorter(a+b), inplace=True)

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