简体   繁体   中英

How to groupby one value of a column in pandas?

I have two columns that look like this:

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

I want to group by only Alfa Romeo and count the Reasons of repair .

Since you only care about one brand, just filter it with loc and get the 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

If you really want to groupby , get the groupby.value_counts() of all brands and select 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM