需要找到按性别分组的流行名称
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)
答案 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)
for key, group in bnames_decade.groupby(['sex']):
print(group['name'].iloc[0:5])
答案 1 :(得分:0)
一个想法是使用sex
和name
的分组并按降序排序。然后使用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