Python 分组排序

Python 分组排序,python,pandas,group-by,pivot-table,Python,Pandas,Group By,Pivot Table,我的数据框中的每一行都是餐厅的用户投票条目。数据看起来像 id cuisine 91 american 3 american 91 american 233 cuban 233 cuban 2 cuban 其中id指餐厅 我想得到如下的东西 american 91 100 3 30 12 10 cuban 233 80

我的数据框中的每一行都是餐厅的用户投票条目。数据看起来像

id   cuisine    
91   american   
3    american   
91   american   
233  cuban      
233  cuban      
2    cuban      
其中
id
指餐厅

我想得到如下的东西

american  91   100
          3    30
          12   10
cuban     233  80
          2    33
mexican   22   99
          8    98
          21   82
其中第2列是
id
,第3列是该
id
的数据帧中的行数。换句话说,按行数排序,但按菜肴分组。我试过了

g = df.groupby(['cuisine', 'id'])
c = g.size().sort_values(ascending=False)
但是菜的顺序是混合的。

这就是你想要的吗

In [2]: df
Out[2]:
    id   cuisine
0   91  american
1    3  american
2   91  american
3  233     cuban
4  233     cuban
5    2     cuban

In [3]: df.groupby(['cuisine', 'id']).size()
Out[3]:
cuisine   id
american  3      1
          91     2
cuban     2      1
          233    2
dtype: int64
或作为数据帧:

In [10]: df.groupby(['cuisine', 'id']).size().reset_index(name='count').sort_values(['cuisine', 'count'], ascending=[1,0])
Out[10]:
    cuisine   id  count
1  american   91      2
0  american    3      1
3     cuban  233      2
2     cuban    2      1
这就是你想要的吗

In [2]: df
Out[2]:
    id   cuisine
0   91  american
1    3  american
2   91  american
3  233     cuban
4  233     cuban
5    2     cuban

In [3]: df.groupby(['cuisine', 'id']).size()
Out[3]:
cuisine   id
american  3      1
          91     2
cuban     2      1
          233    2
dtype: int64
或作为数据帧:

In [10]: df.groupby(['cuisine', 'id']).size().reset_index(name='count').sort_values(['cuisine', 'count'], ascending=[1,0])
Out[10]:
    cuisine   id  count
1  american   91      2
0  american    3      1
3     cuban  233      2
2     cuban    2      1

使用
value\u counts
group\u by
后加
sort\u index

# ascending=[1, 0] says True for level[0], False for level[1]
df.groupby('cuisine').id.value_counts().sort_index(ascending=[1, 0])

cuisine   id 
american  91     2
          3      1
cuban     233    2
          2      1
Name: id, dtype: int64

使用
value\u counts
group\u by
后加
sort\u index

# ascending=[1, 0] says True for level[0], False for level[1]
df.groupby('cuisine').id.value_counts().sort_index(ascending=[1, 0])

cuisine   id 
american  91     2
          3      1
cuban     233    2
          2      1
Name: id, dtype: int64

请发布示例数据框架。查看数据透视表:请发布示例数据框架。查看数据透视表:抱歉,我的示例太简单了。根据我的真实数据,如果我按照你的建议去做,那么菜肴中的计数就不会被排序。@不,我已经更新了我的答案-请检查。请提供详细信息future@nos,请检查-这要好得多。我的例子太简单了。根据我的真实数据,如果我按照你的建议去做,那么菜肴中的计数就不会被排序。@不,我已经更新了我的答案-请检查。请提供详细信息future@nos,请检查-这比默认情况下按降序排序的
值\u counts()
要好得多。即使是最后的排序也可以保存!默认情况下,
值\u counts()
按降序排序。即使是最后的排序也可以保存!