Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python按一列分组,并在另一列中计数字符串_Python_Pandas_Dataframe - Fatal编程技术网

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

Python按一列分组,并在另一列中计数字符串,python,pandas,dataframe,Python,Pandas,Dataframe,我想计算“类型”列中有多少个“AA”,按“卡片”列分组 样本数据 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

我想计算“类型”列中有多少个“AA”,按“卡片”列分组

样本数据

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()

如果要使用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()

如果我理解正确,
df.loc[df.type='AA','card'].value\u counts()
?努力寻找一个重复的问题,但这个问题感觉像是一个普通的问题。你的答案是正确的