python - 分组并找到前 n 个 value_counts Pandas

标签 python pandas dataframe

我有一个出租车数据数据框,其中有两列如下所示:

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/

相关文章:

python - 如何将变量添加到 Keras 中的进度条?

找不到标记的python xml ElementTree异常

python - Pandas - 列值转换

python - Dask dataframe str.contains(regex=True) 不比 pandas 快

python - 计算非常大的功率

python - Pandas 事件序列的动态滚动计数

python - Pandas Dataframe 具有各种列标准的求和函数

python - 理解级别 =0 和 group_keys

python - 合并 Conv2D 和 Dense 模型会导致 "RuntimeError: You must compile your model before using it.",尽管已经编译了合并的模型