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

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

因为你只关心一个牌子,用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()和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