【问题标题】:Pandas dataframe groupby and sort熊猫数据框分组和排序
【发布时间】:2019-07-05 01:12:28
【问题描述】:

我有一个包含 4 列的数据框,其中前两列由字符串(分类变量)组成,最后两列是数字。

Type    Subtype    Price    Quantity
Car     Toyota     10       1
Car     Ford       50       2
Fruit   Banana     50       20
Fruit   Apple      20       5 
Fruit   Kiwi       30       50
Veggie  Pepper     10       20
Veggie  Mushroom   20       10
Veggie  Onion      20       3
Veggie  Beans      10       10  

如何使数据框根据 Type 列上 Price 的聚合总和按降序排序,并让 Price 列的 Subtype 列也按降序排序?像这样:

Type    Subtype    Price    Quantity
Fruit   Banana     50       20
        Kiwi       30       50
        Apple      20       5 
Car     Ford       50       2
        Toyota     10       1
Veggie  Mushroom   20       10
        Onion      20       3
        Beans      10       10  
        Pepper     10       20

我尝试了以下方法,但它没有按降序对 Subtype 列进行排序:

df = df.groupby(['Type','Subtype'])['Price', 'Quantity'].agg({'Price':sum})
i = df.index.get_level_values(0)
df = df.iloc[i.reindex
                   (df['PRICE'].groupby(level=0, 
                   group_keys=False).sum().sort_values('PRICE', ascending=False).index)[1]]
df.columns = df.columns.get_level_values(1)

编辑:子类型下有多个相同的项目,所以我希望类型和子类型列也分组。

【问题讨论】:

  • 预期输出是什么?
  • @jezrael 抱歉,预期的输出是我上面帖子中的第二个数据框。

标签: python pandas pandas-groupby


【解决方案1】:

试试:

df.assign(sortkey = df.groupby('Type')['Price'].transform('sum'))\
  .sort_values(['sortkey','Type','Price'], ascending=[False,True,False])\
  .set_index(['Type','Subtype'])\
  .drop('sortkey', axis=1)

输出:

                 Price  Quantity
Type   Subtype                  
Fruit  Banana       50        20
       Kiwi         30        50
       Apple        20         5
Car    Ford         50         2
       Toyota       10         1
Veggie Mushroom     20        10
       Onion        20         3
       Pepper       10        20
       Beans        10        10

【讨论】:

  • 我如何分组子类型呢?我真的认为也有相同的子类型。
  • 当然,在 sort_values 方法中添加子类型,并且记得在升序列表中添加 True 或 False。
【解决方案2】:

用途:

df_new=df.groupby(['Type','Subtype'],as_index=False).apply(\
                  lambda x:x.sort_values(by='Price',ascending=False)).reset_index(drop=True)

df_new.loc[df_new.Type.duplicated(),'Type']= ''
print(df_new)

     Type   Subtype  Price  Quantity
1     Car      Ford     50         2
0            Toyota     10         1
2   Fruit    Banana     50        20
4              Kiwi     30        50
3             Apple     20         5
6  Veggie  Mushroom     20        10
7             Onion     20         3
5            Pepper     10        20
8             Beans     10        10

【讨论】:

  • 我该如何分组子类型呢?我真的认为也有相同的子类型。
  • 谢谢,但它似乎没有根据价格按类型排序,也没有按子类型列分组
【解决方案3】:

通过sumsort_values 的聚合值创建sorted CategoricalIndex - 在pandas 的最后一个版本中,可以将索引级别与列一起排序:

df = df.groupby(['Type','Subtype'])[['Price', 'Quantity']].sum()

idx = df['Price'].sum(level=0).sort_values().index

i = pd.CategoricalIndex(df.index.get_level_values(0), ordered=True, categories=idx)
df.index = [i, df.index.get_level_values(1)]

df = df.sort_values(['Type','Price'], ascending=False)
print (df)
                 Price  Quantity
Type   Subtype                  
Fruit  Banana       50        20
       Kiwi         30        50
       Apple        20         5
Veggie Mushroom     20        10
       Onion        20         3
       Beans        10        10
       Pepper       10        20
Car    Ford         50         2
       Toyota       10         1

【讨论】:

  • 我该如何分组子类型呢?我真的认为也有相同的子类型。
  • @user112947 - 所以需要df = df.sort_values(['Type','Subtype','Price'], ascending=False) 吗?还是df = df.sort_values(['Type','Subtype','Price'], ascending=[False, True, False])
  • 我收到“KeyError: 'Type'”错误,好像 Type 是一个索引?
  • @user112947 - 也许问题没有使用最新版本的熊猫
猜你喜欢
  • 2012-12-14
  • 2018-07-05
  • 2014-07-11
  • 2018-05-24
  • 2023-02-07
  • 2022-01-20
  • 2017-11-30
  • 2021-10-21
  • 2019-05-03
相关资源
最近更新 更多