Reputation: 1656
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?
Upvotes: 1
Views: 469
Reputation: 1317
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)
Upvotes: 1
Reputation: 323226
After your first sort_values
df.groupby('col1').apply(lambda x: x.sort_values('col2',ascending=False)).reset_index(level=0, drop=True)
Upvotes: 0