首页 > 解决方案 > 对组内的值进行排序

问题描述

假设我有这个数据框:

df = pd.DataFrame({
    'price': [2, 13, 24, 15, 11, 44], 
    'category': ["shirts", "pants", "shirts", "tops", "hat", "tops"],
})
    price   category
0       2     shirts
1      13      pants
2      24     shirts
3      15       tops
4      11        hat
5      44       tops

我想以这样的方式对值进行排序:

最终的数据框如下所示:

    price   category
0      44       tops
1      15       tops
2      24     shirts
3      24     shirts
4      13      pants
5      11        hat

标签: pythonpandas

解决方案


我不是单线的忠实粉丝,所以这是我的解决方案:

# Add column with max-price for each category
df = df.merge(df.groupby('category')['price'].max().rename('max_cat_price'),
              left_on='category', right_index=True)

# Sort
df.sort_values(['category','price','max_cat_price'], ascending=False)

# Drop column that has max-price for each category
df.drop('max_cat_price', axis=1, inplace=True)

print(df)

   price category
5     44     tops
3     15     tops
2     24   shirts
0      2   shirts
1     13    pants
4     11      hat

推荐阅读