首页 > 解决方案 > 在子组列中查找“字符串”的出现并根据其出现标记主组

问题描述

我有看起来像这样的数据:

Group   string
 A     Hello
 A     SearchListing
 A     GoSearch
 A     pen
 A     Hello
 B     Real-Estate
 B     Access
 B     Denied
 B     Group
 B     Group
 C     Glance
 C     NoSearch
 C     Home

等等

我想找出所有在字符串中有“搜索”短语的组并将它们标记为 0/1。同时,我想汇总每个组的唯一字符串和总字符串等结果,以及该组遇到多少次“搜索”。我想要的最终结果是这样的:

Group   containsSearch  TotalStrings  UniqueStrings  NoOfTimesSearch
 A           1              5             4              2
 B           0              5             4              0
 C           1              3             3              1 

我可以使用简单的 groupby 子句进行聚合,但我在如何根据“搜索”的存在将组标记为 0/1 并计算遇到的次数时遇到问题。

标签: pythonpandasnumpygroup-bypandas-groupby

解决方案


我们试试看:

l1 = lambda x: x.str.lower().str.contains('search').any().astype(int)
l1.__name__ = 'containsSearch'
l2 = lambda x: x.str.lower().str.contains('search').sum().astype(int)
l2.__name__ = 'NoOfTimesSEarch'

df.groupby('Group')['string'].agg(['count','nunique',l1,l2]).reset_index()

输出:

  Group  count  nunique  containsSearch  NooOfTimesSEarch
0     A      5        4               1                2
1     B      5        4               0                0
2     C      3        3               1                1

或者使用定义的函数谢谢@WB:

def conatinsSearch(x):
    return x.str.lower().str.contains('search').any().astype(int)

def NoOfTimesSearch(x):
    return x.str.lower().str.contains('search').sum().astype(int)


df.groupby('Group')['string'].agg(['count', 'nunique',
                                   conatinsSearch, NoOfTimesSearch]).reset_index()

输出:

  Group  count  nunique  conatinsSearch  NoOfTimesSearch
0     A      5        4               1                2
1     B      5        4               0                0
2     C      3        3               1                1

推荐阅读