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