2015-07-12 52 views
0

對於這種數據的隨着熊貓在Python,我怎麼樣通過由AGG函數創建兩列?

author  cat val 
0 author1 category2 15 
1 author2 category4 9 
2 author3 category1 7 
3 author4 category1 9 
4 author5 category2 11 

我想

 cat mean count 
category2 13  2 
category1 8  2 
category4 9  1 

我想我在熊貓越來越好,並寫了

most_expensive_standalone.groupby('cat').apply(['mean', 'count']).sort(['count', 'mean']) 

,但得到

File "/home/mike/anaconda/lib/python2.7/site-packages/pandas/core/groupby.py", line 3862, in _intercept_function 
    return _func_table.get(func, fnc) 
TypeError: unhashable type: 'list' 

回答

2

您應該使用.agg,而不是.apply,如果你只是想傳遞兩個聚合函數meancount您的數據。此外,因爲你已經在同一列val應用兩個功能,將引入一個多層次的列索引。因此,排序上新創建的列meancount之前,您需要選擇它的外部級val第一。

most_expensive_standalone.groupby('cat').agg(['mean', 'count'])['val'].sort(['mean', 'count'] 


      mean count 
cat     
category1  8  2 
category4  9  1 
category2 13  2 

後續處理:

# just perform groupby and .agg will give you this 
most_expensive_standalone.groupby('cat').agg(['mean', 'count']) 

      val  
      mean count 
cat     
category1 8  2 
category2 13  2 
category4 9  1 

選擇val

most_expensive_standalone.groupby('cat').agg(['mean', 'count'])['val'] 


      mean count 
cat     
category1  8  2 
category2 13  2 
category4  9  1 

最後調用.sort(['mean', 'count'])

+0

作品!你介意多說一點嗎? 「因此,在對新創建的列進行排序之前,您需要先選擇其外層val。」 – Mike

+0

@Mike我更新了帖子。請看一看。 :-) –

+0

非常感謝,夥計!但是,如何選擇只是val列不會丟失貓列? – Mike