我有一个包含这样的列的数据框:
id lead_sponsor lead_sponsor_class
02837692 Janssen Research & Development, LLC Industry
02837679 Aarhus University Hospital Other
02837666 Universidad Autonoma de Ciudad Juarez Other
02837653 Universidad Autonoma de Madrid Other
02837640 Beirut Eye Specialist Hospital Other
我想找到最常见的主要赞助商。我可以使用以下方式列出每个组的大小:
df.groupby(['lead_sponsor', 'lead_sponsor_class']).size()
给了我这个:
lead_sponsor lead_sponsor_class
307 Hospital of PLA Other 1
3E Therapeutics Corporation Industry 1
3M Industry 4
4SC AG Industry 8
5 Santé Other 1
但我怎样才能找到十大最常见的群体?如果我这样做:
df.groupby(['lead_sponsor', 'lead_sponsor_class']).size().sort_values(ascending=False).head(10)
然后我收到错误:
AttributeError:'Series'对象没有属性'sort_values'
答案 0 :(得分:2)
我认为您可以使用Series.nlargest
:
print (df.groupby(['lead_sponsor', 'lead_sponsor_class']).size().nlargest(10))
在docs中备注:
相对于Series对象的大小,小于n的.sort_values(升序=假).head(n)更快。
样品:
import pandas as pd
df = pd.DataFrame({'id': {0: 2837692, 1: 2837679, 2: 2837666, 3: 2837653, 4: 2837640},
'lead_sponsor': {0: 'a', 1: 'a', 2: 'a', 3: 's', 4: 's'},
'lead_sponsor_class': {0: 'Industry', 1: 'Other', 2: 'Other', 3: 'Other', 4: 'Other'}})
print (df)
id lead_sponsor lead_sponsor_class
0 2837692 a Industry
1 2837679 a Other
2 2837666 a Other
3 2837653 s Other
4 2837640 s Other
print (df.groupby(['lead_sponsor', 'lead_sponsor_class']).size())
lead_sponsor lead_sponsor_class
a Industry 1
Other 2
s Other 2
dtype: int64
print (df.groupby(['lead_sponsor', 'lead_sponsor_class']).size().sort_values(ascending=False).head(2))
lead_sponsor lead_sponsor_class
s Other 2
a Other 2
dtype: int64
print (df.groupby(['lead_sponsor', 'lead_sponsor_class']).size().nlargest(2))
lead_sponsor lead_sponsor_class
a Other 2
s Other 2
dtype: int64