1

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?

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

After your first sort_values

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.