我想计算一个分组的pandas 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
首先,我想按catA
和catB
分组。对于这些组中的每个组,我希望在scores
列中计算RET
的出现次数。
结果应该如下所示:
catA catB RET
A X 1
A Y 1
B Z 2
按两列分组很容易:grouped = df.groupby(['catA', 'catB'])
但是下一步呢?
发布于 2015-07-27 17:43:03
对groupby
对象的'scores‘列调用apply
,并使用矢量化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
https://stackoverflow.com/questions/31649669
复制相似问题