簡體   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