首页 > 解决方案 > 检查 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"))]

非常感谢任何帮助和指导。

标签: pythonstringpandas

解决方案


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]

推荐阅读