繁体   English   中英

如何对 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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