2015-07-12 57 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