Group by and find top n value_counts pandas

后端 未结 4 1506
终归单人心
终归单人心 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 12:43

    I think you can use nlargest - you can change 1 to 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
    

    additional columns were getting created, specified level info

提交回复
热议问题