简体   繁体   English

Pandas - 如何使用 2 个不同的键按 2 个不同的列对值进行排序

[英]Pandas - How to sort_values by 2 different columns using 2 different keys

Pandas 1.1.0 added the key paramater to sort_values . Pandas 1.1.0 key参数添加到sort_values

Is it possible to sort by 2 different columns, and use a different key for each?是否可以按 2 个不同的列排序,并为每个列使用不同的key

If not - what would be the best way to achieve this same behavior?如果不是 - 实现相同行为的最佳方法是什么?

After your first sort_values在你的第一个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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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