我有一个出租车数据数据框,其中有两列如下所示:
Neighborhood Borough Time
Midtown Manhattan X
Melrose Bronx Y
Grant City Staten Island Z
Midtown Manhattan A
Lincoln Square Manhattan B
基本上,每一行代表该行政区该街区的出租车接送服务。现在,我想找出每个行政区中上客次数最多的前 5 个社区。我试过这个:
df['Neighborhood'].groupby(df['Borough']).value_counts()
这给了我这样的东西:
borough
Bronx High Bridge 3424
Mott Haven 2515
Concourse Village 1443
Port Morris 1153
Melrose 492
North Riverdale 463
Eastchester 434
Concourse 395
Fordham 252
Wakefield 214
Kingsbridge 212
Mount Hope 200
Parkchester 191
......
Staten Island Castleton Corners 4
Dongan Hills 4
Eltingville 4
Graniteville 4
Great Kills 4
Castleton 3
Woodrow 1
我如何过滤它,以便我只得到前 5 个?我知道有几个标题相似的问题,但它们对我的情况没有帮助。
最佳答案
我认为你可以使用 nlargest
- 你可以把 1
改成 5
:
s = df['Neighborhood'].groupby(df['Borough']).value_counts()
print s
Borough
Bronx Melrose 7
Manhattan Midtown 12
Lincoln Square 2
Staten Island Grant City 11
dtype: int64
print s.groupby(level=[0,1]).nlargest(1)
Bronx Bronx Melrose 7
Manhattan Manhattan Midtown 12
Staten Island Staten Island Grant City 11
dtype: int64
正在创建其他列,指定级别信息
关于python - 分组并找到前 n 个 value_counts Pandas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35364601/