python - Flag if the last element in a group contain particular string in Pandas
问题描述
I have data:
Group string
A Hello
A SearchListing
A GoSearch
A pen
A Hello
A Searches
B Real-Estate
B Access
B Denied
B Group
B Group
C Glance
C NoSearch
C Home
C FullSearch
and so on.
I want to find those group which has a string containing "search" as their last element and flag them. For example, the output i want is something like this:
Group Flag
A 1
B 0
C 1
as both A and C had their last element containing string "search". I know of a method which can iterate through all the elements and if last element contains "search" it will flag it. But its a very heavy function using loops. Is there a more straight forward way for this?
解决方案
使用str.contains
:
(df.groupby('Group')['string']
.last()
.str.contains('search', case=False)
.astype(int)
.rename('Flag')
.reset_index())
Group Flag
0 A 1
1 B 0
2 C 1
与上面类似(复制或重置索引以避免SettingWithCopyWarning
)。
u = df.drop_duplicates('Group', keep='last').reset_index(drop=True)
u['Flag'] = u.pop('string').str.contains('search', case=False).astype(int)
u
Group Flag
0 A 1
1 B 0
2 C 1
推荐阅读
- c# - 用等效的枚举值自动替换数字常量?
- azure - 是否可以将上传的图片用于 OCR 分析存储在 azure 存储中以供以后调试和分析?
- c# - C# - 如何将每个击键逐行保存到文件中
- windows - 从 Visual Studio 2019 IDE 启动提示时,为什么 wsl(Linux 的 Windows 子系统)在命令提示符中不可用?
- python - 带有命名参数的 PySide2 (5.14.2) 信号
- java - 从 MongoDB 数据库 (JAVA) 更新/刷新 JavaFX 标签
- python-3.x - 有没有计算六面体质心的函数
- excel - 在 Excek VBA 代码中使用 SUM 函数时出错
- javascript - 如何让 JHipster 使用 Javascript 而不是 Typescript 进行 React
- java - Android Studio`找不到ID为'com.android.application'的插件`