如何对熊猫中一列的一个值进行分组?

青葱年少 python 183

原文标题How to groupby one value of a column in pandas?

我有两列看起来像这样:

Vehicle Brand      Reason of repair

Alfa Romeo         Brakes not working
Honda              Annual Service
BMW                Other
Alfa Romeo         Electrical issues
Honda              Paint
Alfa Romeo         Annual service
Alfa Romeo         Annual service

我只想按Alfa Romeo分组并计算Reasons of repair

原文链接:https://stackoverflow.com//questions/71521977/how-to-groupby-one-value-of-a-column-in-pandas

回复

我来回复
  • tdy的头像
    tdy 评论

    由于您只关心一个品牌,只需用loc对其进行过滤并获得value_counts()

    df.loc[df['Vehicle Brand'] == 'Alfa Romeo', 'Reason of repair'].value_counts()
    
    # Annual service        2
    # Brakes not working    1
    # Electrical issues     1
    # Name: Reason of repair, dtype: int64
    

    如果你真的想groupby,就拿到所有品牌的groupby.value_counts(),然后选择Alfa Romeo

    df.groupby('Vehicle Brand')['Reason of repair'].value_counts().loc['Alfa Romeo']
    
    # Reason of repair
    # Annual service        2
    # Brakes not working    1
    # Electrical issues     1
    # Name: Reason of repair, dtype: int64
    
    2年前 0条评论