python - 检查 DataFrame 字符串值是否包含具有某些前缀的单词
问题描述
第一次使用 Pandas,我正在努力为这个规范查询 DataFrame。
假设我创建了一个数据框,如下所示:
df = pd.read_csv(_file, names=['UID', 'Comment', 'Author', 'Relevancy'])
这使:
UID . Comment . Author . Relevancy
1234 . motorcycles are cool . dave . 12
5678 . motorhomes are cooler . mike . 13
9101 . i love motorbikes . frank . 14
当我查询“电机”这个词时,我需要返回所有这些行。
即,如果它的“注释”字符串包含以给定单词为前缀的单词,则应返回一行。
我基本上想做类似的事情:
df["Comment"][any(word in df["Comment"].str.split() if word.startswith("motor"))]
非常感谢任何帮助和指导。
解决方案
Pandasstr
操作未矢量化。您可以使用列表推导:
df = pd.DataFrame({'Comment': ['motorcycles are cool', 'motorhomes are cooler',
'i love motorbikes', 'nomotor test string',
'some other test string']})
flag = [any(w.startswith('motor') for w in x.casefold().split()) for x in df['Comment']]
res = df.loc[flag]
print(res)
Comment
0 motorcycles are cool
1 motorhomes are cooler
2 i love motorbikes
使用 Pandasstr
方法的效率较低的版本是可能的:
def check_words(x):
return any(w.startswith('motor') for w in x)
flag = df['Comment'].str.lower().str.split().map(check_words)
res = df.loc[flag]
推荐阅读
- search - 如何在 Delphi TBCEditor 中搜索和替换代码
- javascript - React.js:从对象数组渲染组件
- html - 绝对 iframe 网址问题
- java - 如何在 Java 中附加到 gzip 文件的末尾?
- linux - ansible shell Linux
- ruby-on-rails - 如何使用 Rails 压缩和保存从 API 接收到的 JSON 数据
- python - Scrapy:网站正在减慢我的请求
- ruby-on-rails - 在 rspec 中正确存根方法
- javascript - 如何从复选框输入中检索真/假?
- mysql - 在 CentOS 8 上安装 mysql-server 时出错