pandas对值进行排序,以获得groupby中每列的前5位

时间:2018-04-03 14:01:19

标签: python pandas group-by

我有一个包含城市,名称和成员的数据框。我需要根据每个城市的最高成员('成员')数来找到前5个组(名称)。

这是我使用时得到的:

clust.groupby(['city','name']).agg({'members':sum})

members city name Bath AWS Bath User Group 346 Agile Bath & Bristol 957 Bath Crypto Chat 47 Bath JS 142 Bath Machine Learning Meetup 435 Belfast 4th Industrial Revolution Challenge 609 Belfast Adobe Meetup 66 Belfast Azure Meetup 205 Southampton Crypto Currency Trading SouthCoast 50 Southampton Bitcoin and Altcoin Meetup 50 Southampton Functional Programming Meetup 28 Southampton Virtual Reality Meetup 248 Sunderland Sunderland Digital 287

我需要前五名,但你可以看到成员数似乎没有被命令,即957之前的346等。

我之前尝试过对值进行排序并执行:

clust.sort_values(['city', 'name'], axis=0).groupby('city').head(5)

但这会返回类似的系列。

我也使用了这个clust.groupby(['city', 'name']).head(5)

但是它给了我所有的行而不是前5行。它的结构也不是按字母顺序排列的。

请帮忙。感谢

1 个答案:

答案 0 :(得分:3)

我认为需要将ascending=[True, False]添加到sort_values并将列更改为members以进行排序:

clust = clust.groupby(['city','name'], as_index=False)['members'].sum()
df = clust.sort_values(['city', 'members'], ascending=[True, False]).groupby('city').head(5)
print (df)

           city                                 name  members
1          Bath                 Agile Bath & Bristol      957
4          Bath              Machine Learning Meetup      435
0          Bath                  AWS Bath User Group      346
3          Bath                                   JS      142
2          Bath                          Crypto Chat       47
5       Belfast  4th Industrial Revolution Challenge      609
7       Belfast                         Azure Meetup      205
6       Belfast                         Adobe Meetup       66
11  Southampton               Virtual Reality Meetup      248
8   Southampton   Crypto Currency Trading SouthCoast       50
9   Southampton           Bitcoin and Altcoin Meetup       50
10  Southampton        Functional Programming Meetup       28
12   Sunderland                   Sunderland Digital      287