大熊猫对groupby的值进行排序

时间:2021-04-03 22:13:08

标签: python pandas sorting pandas-groupby

我有一组关于足球的数据:

dataset

我按照每个场地上的比赛数量排序:

fb2 = fb.groupby(by=['Ground'])['Ground'].count()
print(fb2)

输出:

Ground
Aberdeen         11
Abu Dhabi        37
Adelaide         82
Ahmedabad        24
Albion            5
                 ..
Vijayawada        1
Visakhapatnam    11
Wellington       56
Whangarei         1
Worcester         3
Name: Ground, Length: 173, dtype: int64

现在我想对结果进行排序,按照每个场地进行了多少场比赛的降序排列。

我对 python 很陌生...任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:4)

如果你使用命名聚合,你可以指定一个列名来排序:

fb2 = (
  fb
  .groupby('Ground', as_index=False)
  .agg(n_matches=('Ground', 'count'))
  .sort_values('n_matches, ascending=False)
)

答案 1 :(得分:0)

fb.groupby(by=['Ground'])['Ground'].count() 的类型是系列,可以使用 pandas.Series.sort_values() 进行排序

fb.groupby(by=['Ground'])['Ground'].count().sort_values(ascending=False))