我的 DataFrame 中的每一行都是用户对餐厅的投票条目。数据看起来像
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
在 DataFrame 中的行数。换句话说,按行数排序,但按美食分组。我试过了
g = df.groupby(['cuisine', 'id'])
c = g.size().sort_values(ascending=False)
但是菜系的顺序是混杂的。
最佳答案
在 group_by
之后使用 value_counts
后跟 sort_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
关于python pandas 按组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38464142/