繁体   English   中英

pandas groupby计数字符串出现在列上

[英]pandas groupby count string occurrence over column

我想计算分组的pandas dataframe列中字符串的出现次数。

假设我有以下Dataframe:

catA    catB    scores
A       X       6-4 RET
A       X       6-4 6-4
A       Y       6-3 RET
B       Z       6-0 RET
B       Z       6-1 RET

首先,我想通过catAcatB 对于这些组中的每一组,我想计算scores列中RET的出现次数。

结果应如下所示:

catA    catB    RET
A       X       1
A       Y       1
B       Z       2

按两列分组很简单: grouped = df.groupby(['catA', 'catB'])

但下一步是什么?

调用apply上的“成绩”栏上groupby对象,并使用vectorise str方法contains ,使用此过滤group并调用count

In [34]:    
df.groupby(['catA', 'catB'])['scores'].apply(lambda x: x[x.str.contains('RET')].count())

Out[34]:
catA  catB
A     X       1
      Y       1
B     Z       2
Name: scores, dtype: int64

要指定为列使用transform以便聚合返回一个系列,其索引与原始df对齐:

In [35]:
df['count'] = df.groupby(['catA', 'catB'])['scores'].transform(lambda x: x[x.str.contains('RET')].count())
df

Out[35]:
  catA catB   scores count
0    A    X  6-4 RET     1
1    A    X  6-4 6-4     1
2    A    Y  6-3 RET     1
3    B    Z  6-0 RET     2
4    B    Z  6-1 RET     2

暂无
暂无

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

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