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?
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?
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)