在Python中,如何按agg函数创建的两列进行排序?

在Python中,如何按agg函数创建的两列进行排序?,python,pandas,Python,Pandas,对于这类数据 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

对于这类数据

    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'

如果只想将两个聚合函数
mean
count
传递给数据,则应使用
.agg
代替
。apply
。此外,由于在同一列
val
上应用了两个函数,因此它将引入多级列索引。因此,在对新创建的列
mean
count
进行排序之前,您需要首先选择其外部级别
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'])

有效!你介意再解释一下吗?“因此,在对新创建的列mean和count进行排序之前,您需要先选择其外部级别val。”@Mike我已经更新了帖子。请看一看。:-)非常感谢,伙计!但是为什么只选择val列不会丢失cat列呢?@Mike cat是索引而不是列。索引位于轴=0上,而列位于轴=1上。