【问题标题】:Sort values intra group [duplicate]对组内的值进行排序[重复]
【发布时间】:2021-04-13 05:51:34
【问题描述】:

假设我有这个数据框:

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

【问题讨论】:

  • 如今,一只好的 pandas MRE 已经很少见了。 +1 用于简单、最少的数据帧代码

标签: python pandas


【解决方案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

【讨论】:

    【解决方案2】:

    您可以使用.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
    
    

    【讨论】:

      【解决方案3】:

      我在数据框中使用 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-03
        • 2017-12-02
        相关资源
        最近更新 更多