如何对熊猫中一列的一个值进行分组?
python 283
原文标题 :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
。
回复
我来回复-
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年前