python - 查找与列表匹配的子字符串
问题描述
如何找到与df
列值匹配的所有子字符串?
text = "The quick brown fox jumps over the lazy dog"
df = pd.DataFrame(['quick brown fox', 'jump', 'lazy dog', 'banana', 'quick fox'], columns=['value'])
results = get_matches(df, text)
# Excepted results: ['quick brown fox', 'jump', 'lazy dog']
解决方案
一种选择:
import pandas as pd
text = "The quick brown fox jumps over the lazy dog"
df = pd.DataFrame(['quick brown fox', 'jump', 'lazy dog', 'banana', 'quick fox'], columns=['value'])
def get_matches(df, text):
return df[df['value'].apply(text.__contains__)]
res = get_matches(df, text)
print(res)
输出
value
0 quick brown fox
1 jump
2 lazy dog
作为替代方案,使用str.find:
def get_matches(df, text):
return df[df['value'].apply(text.find).ne(-1)]
res = get_matches(df, text)
print(res)
输出
value
0 quick brown fox
1 jump
2 lazy dog
推荐阅读
- amazon-web-services - 有没有什么优雅的方法可以以最小的延迟跨 aws 区域复制 redis 数据?
- ios - Xamarin.iOS - 发布应用程序 - 无效的 Swift 支持 - 文件......不匹配
- ruby-on-rails - 需要使用 rails 将 post_id 和 user_id 存储在 read_statuses 表中
- xamarin.android - 如何手动添加额外的文本视图而不将其添加到 axml
- graphql - 数据加载器 facebook 优化
- node.js - 如何将 nodejs 服务托管到 VirtualMachine 中的 nginx 服务器中?
- vue.js - Vuejs - 从表中读取数据
- android - 在后台以及屏幕关闭时录制视频
- jquery - jQuery从选择中获取文本而不是值,并在页面加载时检查初始值
- c++ - c_str 的奇怪行为?