python-打印每组的前5名

时间:2018-02-27 19:12:28

标签: python pandas sorting pandas-groupby

需要找到按性别分组的流行名称

bnames_decade = bnames_decade.groupby(['sex','name'])['births'].sum().sort_values(ascending=False)

这显示

F    Emma        121375
     Sophia      117352
     Olivia      111691
M    Noah        110280
     Mason       105104
     Jacob       104722
F    Isabella    103947

...

我想打印每组的前5名。 任何人都可以建议使用Python编码吗?

我尝试的方式不起作用。

bnames_top5 =bnames_decade.groupby('sex').head(5)

2 个答案:

答案 0 :(得分:0)

import pandas as pd
bnames_decade = pd.DataFrame([['F','Emma',121375],['F','Sophia',117352],['F','Olivia',111691],['M','Noah',110280],['M','Mason',105104],['F','Isabella',103947], ['F','Isabella2',103946],['F','Isabella3',103945],['F','Isabella4',103944],['M','Isabella5',103943],['M','Isabella6',103942],['M','Isabella7',103941],['M','Isabella8',103940]], columns=['sex','name','births'])
print(bnames_decade)

enter image description here

for key, group in bnames_decade.groupby(['sex']):
    print(group['name'].iloc[0:5])

enter image description here

答案 1 :(得分:0)

一个想法是使用sexname的分组并按降序排序。然后使用GroupBy执行另一个head。这是一个示例:

df = pd.DataFrame({'sex': ['F', 'F', 'F', 'M', 'M', 'M', 'F', 'F', 'F', 'M', 'M', 'M'],
                   'name': ['Ursula', 'Jane', 'Edith', 'Leo', 'Brian', 'Philip',
                            'Ursula', 'Edith', 'Daphne', 'Leo', 'Brian', 'George']})

df = df.groupby(['sex', 'name']).size().sort_values(ascending=False).reset_index()

res = df.groupby('sex').head(2)

print(res)

  sex    name  0
0   M     Leo  2
1   M   Brian  2
2   F  Ursula  2
3   F   Edith  2