python - 检查 DataFrame 字符串值包含具有特定前缀的单词

标签 python string pandas

第一次使用 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

当我查询“motor”一词时,我需要返回所有这些行。

即如果“Comment”字符串包含以给定单词为前缀的单词,则应返回一行。

我本质上想做这样的事情:

df["Comment"][any(word in df["Comment"].str.split() if word.startswith("motor"))]

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

最佳答案

Pandas str 操作未矢量化。您可以使用列表理解:

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

使用 Pandas str 方法的效率较低的版本是可能的:

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]

关于python - 检查 DataFrame 字符串值包含具有特定前缀的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53548791/

相关文章:

python - 从文本文件中获取整数并用python写入excel

excel - 如何将多个句子中的每个单词放入Excel中的文本单元格?

c# - 使用 .net 正则表达式替换字符串中的文本

string - 如何使用批处理查看字符串是否包含子字符串

python - 如何使用 pandas 将 200.13K 和 1.2M 等数字字符串转换为整数?

python - 如何更改列的值

python - 从 Pandas DataFrame 创建一个篮子——不是标准的交易数据集

python - Django Blob 模型字段

python - Django MySql 原始查询错误 - 参数索引超出范围

python - 如何更新pytest的源文件?