熊猫数据框分组和排序

时间:2019-02-11 14:04:42

标签: python pandas pandas-groupby

我有一个包含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  

如何使数据框根据“类型”列上“价格”的总和按降序排序,并且对“价格”列也使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)

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

3 个答案:

答案 0 :(得分:4)

尝试:

$array = array(
0 => array(
    'from' => '2019-01-01 00:00:00',
    'to' => '2019-02-03 23:59:59'
),
1 => array(
    'from' => '2019-02-04 00:00:00',
    'to' => '2019-03-14 23:59:59'
),
2 => array(
    'from' => '2019-03-15 00:00:00',
    'to' => '2019-03-31 00:00:00'
));

输出:

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)

答案 1 :(得分: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

答案 2 :(得分:2)

先用sorted CategoricalIndex然后再用sort_values的聚合值创建sum-在最新版本的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