2017-04-02 85 views
10

在Python,我有类似如下的熊猫数据帧:Python的大熊猫GROUPBY多个列骨料,然后转动

Item | shop1 | shop2 | shop3 | Category 
------------------------------------ 
Shoes| 45 | 50 | 53 | Clothes 
TV | 200 | 300 | 250 | Technology 
Book | 20 | 17 | 21 | Books 
phone| 300 | 350 | 400 | Technology 

凡shop1,SHOP2和shop3在不同的商店每一个项目的成本。 现在,我需要返回一个数据帧,一些数据清理后,像这样的:

Category (index)| size| sum| mean | std 
---------------------------------------- 

其中size是在每个类别和项目的数量,平均和性病相关的应用到同样的功能这3家商店。如何使用拆分应用组合模式(groupby,aggregate,apply,...)执行这些操作?

有人可以帮我吗?我会为这个疯狂...谢谢你!

回答

10

选项1个
使用agg←链接文档

agg_funcs = dict(Size='size', Sum='sum', Mean='mean', Std='std') 
df.set_index(['Category', 'Item']).stack().groupby(level=0).agg(agg_funcs) 

        Std Sum  Mean Size 
Category          
Books  2.081666 58 19.333333  3 
Clothes  4.041452 148 49.333333  3 
Technology 70.710678 1800 300.000000  6 

选项2
多予少取
使用describe←链接文档

df.set_index(['Category', 'Item']).stack().groupby(level=0).describe().unstack() 

      count  mean  std min 25% 50% 75% max 
Category                 
Books   3.0 19.333333 2.081666 17.0 18.5 20.0 20.5 21.0 
Clothes  3.0 49.333333 4.041452 45.0 47.5 50.0 51.5 53.0 
Technology 6.0 300.000000 70.710678 200.0 262.5 300.0 337.5 400.0 
2
df.groupby('Category').agg({'Item':'size','shop1':['sum','mean','std'],'shop2':['sum','mean','std'],'shop3':['sum','mean','std']}) 

或者,如果你希望它横跨那么所有的商店:

df1 = df.set_index(['Item','Category']).stack().reset_index().rename(columns={'level_2':'Shops',0:'costs'}) 
df1.groupby('Category').agg({'Item':'size','costs':['sum','mean','std']}) 
0

如果我理解正确的话,你要计算综合指标所有的商店,而不是各自独立。要做到这一点,你可以先stack您的数据框,然后按Category

stacked = df.set_index(['Item', 'Category']).stack().reset_index() 
stacked.columns = ['Item', 'Category', 'Shop', 'Price'] 
stacked.groupby('Category').agg({'Price':['count','sum','mean','std']}) 

导致

  Price        
      count sum  mean  std 
Category          
Books   3 58 19.333333 2.081666 
Clothes  3 148 49.333333 4.041452 
Technology  6 1800 300.000000 70.710678