python - 在子组列中查找“字符串”的出现并根据其出现标记主组
问题描述
我有看起来像这样的数据:
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 并计算遇到的次数时遇到问题。
解决方案
我们试试看:
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
推荐阅读
- css - 您如何有条件地将多个类应用于单个 Material UI 类道具
- python - discord py - 如果用户回复我的机器人,则发送不同的消息
- javascript - Understanding LinkedLists References
- hashicorp-vault - Hashicorp Vault Policy is not getting assigned
- python - 什么时候可以在定义之前使用名称?
- python - 使用圆形掩码进行平均
- database - Making manually-added cells automatically move along with imported ranges in Google Sheets?
- python - Python“AttributeError:'Popen'对象没有属性'sderr'”错误Python 3.9
- node.js - 应用程序正在侦听,但 socket.io 不会连接
- python - 在两个不同的 pandas 数据帧之间搜索和替换值