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

pandas groupby计数字符串出现在列上,第1张

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

调用对象

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  catBA     X       1      Y       1B     Z       2Name: scores, dtype: int64

要将其分配为列使用,

transform
以便聚合返回其索引与原始df对齐的序列:

In [35]:df['count'] = df.groupby(['catA', 'catB'])['scores'].transform(lambda x: x[x.str.contains('RET')].count())dfOut[35]:  catA catB   scores count0    A    X  6-4 RET     11    A    X  6-4 6-4     12    A    Y  6-3 RET     13    B    Z  6-0 RET     24    B    Z  6-1 RET     2


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5645517.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存