pandas 对值进行排序以获取 groupby 中每列的前 5 个值

sno*_*all 4 python group-by pandas

我有一个包含城市、名称和成员的数据框。我需要根据每个城市的最高成员(“成员”)数量找到前 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

我需要前 5 名,但正如你所看到的,成员数量似乎没有排序,即 346 名在 957 名之前,等等。

我还尝试预先对值进行排序并执行以下操作:

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

但这会返回一个类似的系列。

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

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

请帮忙。谢谢

jez*_*ael 7

我认为需要添加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
Run Code Online (Sandbox Code Playgroud)