Group by and find top n value_counts pandas

后端 未结 4 1482
终归单人心
终归单人心 2020-12-25 12:04

I have a dataframe of taxi data with two columns that looks like this:

Neighborhood    Borough        Time
Midtown         Manhattan      X
Melrose         B         


        
4条回答
  •  醉梦人生
    2020-12-25 13:00

    You can do this in a single line by slightly extending your original groupby with 'nlargest':

    >>> df.groupby(['Borough', 'Neighborhood']).Neighborhood.value_counts().nlargest(5)
    Borough        Neighborhood    Neighborhood  
    Bronx          Melrose         Melrose           1
    Manhattan      Midtown         Midtown           1
    Manhatten      Lincoln Square  Lincoln Square    1
                   Midtown         Midtown           1
    Staten Island  Grant City      Grant City        1
    dtype: int64
    

提交回复
热议问题