按组内排序数值

3

假设我有这个数据框:

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

2
现在很难看到一个好的pandas MRE。对于简单、最小化的数据框代码,点个赞。 - Tomerikoo
3个回答

1

我不是一个喜欢使用一行代码的人,所以这是我的解决方案:

# 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

0
你可以使用 .groupby.sort_values
df.join(df.groupby("category").agg("max"), on="category", rsuffix="_r").sort_values(
    ["price_r", "price"], ascending=False
)

输出

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


0

我在数据框的 apply 中使用了 get_group 来获取一个类别的最高价格

 df = pd.DataFrame({
'price': [2, 13, 24, 15, 11, 44], 
'category': ["shirts", "pants", "shirts", "tops", "hat", "tops"],
 })
 grouped=df.groupby('category')

 df['price_r']=df['category'].apply(lambda row: grouped.get_group(row).price.max())
 df=df.sort_values(['category','price','price_r'], ascending=False)
 print(df)

输出

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接