2017-04-02 79 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