组内排序值

2024-09-26 22:51:16 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这个数据帧:

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

Tags: 数据dataframedf排序hat方式价格类别
3条回答

我在数据帧应用中使用了get_组来获取类别的最大价格

 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

您可以使用^{}^{}

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

我不太喜欢一行程序,所以我的解决方案是:

# 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

相关问题 更多 >

    热门问题