python - 使用字符串方法过滤列值上的行
问题描述
输入 df:
title desc
movie A It is a awesome movie with action
movie B Slow but intense movie.
我想过滤包含以下关键字的行:
keys = ["awesome", "action"]
输出DF:
title desc
movie A It is a awesome movie with action
代码:
index_list = []
for index,rows in df.iterrows():
if any(x in rows["desc"].split(" ") for x in keys) == True:
index_list.append(index)
df = df.loc[index_list]
方法:
In each row, I am checking if any of the keywords are present after splitting the rows
这种方法效果很好,但我很想知道 pandas 中是否有任何一种衬垫可以达到同样的效果。
例子:
df.loc[df['column_name'].isin(some_values)]
解决方案
为什么是的,有 - pandas.Series.str.contains
idx = df['column_name'].str.contains("|".join(keys), regex=True)
df[idx]
推荐阅读
- c++ - 为什么这个对象不必调用它的构造函数?
- ssl-certificate - Discord.py 证书验证失败:
- mysql - 当我在 Mysql 中尝试在我的表中进行部分搜索时,它给了我 Error Empty set (0.00 sec)
- python - 使用 pandas 从 datetime 对象转换从午夜开始的毫秒数
- c# - Unity 2D Trigger 只能由一个 Player Prefab 触发
- azure - Azure.Storage.Blobs.BlobServiceClient CopyFromUri() 在返回最新的 ETag 之前似乎没有完成复制
- javascript - JS:不确定为什么函数返回
- reactjs - 从域调用时,Firebase 函数不执行
- python - Python WebScraping FlashScore
- ios - 如何使用附加数据将 apns 令牌发送到服务器