繁体   English   中英

熊猫对值进行排序以使groupby中的每一列排在前5位

[英]pandas sort values to get top 5 for each column in a groupby

我有一个包含城市,名称和成员的数据框。 我需要按每个城市的最高会员数(“会员”)找到前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名,但正如您所看到的那样,会员人数似乎没有排序,即957年之前是346位,依此类推。

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

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

但这返回了类似的系列。

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

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

请帮忙。 谢谢

我认为需要将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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM