Python按列分组,并在另一列中计数字符串

2024-10-03 23:28:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想数一数“type”列中有多少个“AA”,按“card”列分组

样本数据

index   card    type
0       88       AA
1       88       AA
2       88       dsv
3       44       AA
4       44       AA
5       44       AA
6       44      yoyp
7       44      yoyp

预期产量

card type
88    2
44    3

我的方法行得通,但我想学一种更好的方法

d= df[df.type== 'AA']

然后我用groupby

d.groupby(['card']).type.count()

Tags: 数据方法dfindextypecountcardaa
2条回答

如果你想使用groupby

 df.loc[df['type']=='AA'].groupby('card')['type'].agg({'count'})
 #output
       count
  card  
  44    3
  88    2

用户@miradulo的回答很好

df.loc[df.type == 'AA', 'card'].value_counts()

相关问题 更多 >