【发布时间】:2019-11-30 12:35:41
【问题描述】:
我有一个带有文本的大型数据框,我想用它来从单词列表(其中大约 1k 个单词)中查找匹配项。
我已经设法从数据框中的列表中获取单词的缺失/存在,但知道哪个单词匹配对我来说也很重要。有时与列表中的多个单词完全匹配,我想拥有它们。
我尝试使用下面的代码,但它给了我部分匹配 - 音节而不是完整的单词。
#this is a code to recreate the initial DF
import pandas as pd
df_data= [['orange','0'],
['apple and lemon','1'],
['lemon and orange','1']]
df= pd.DataFrame(df_data,columns=['text','match','exact word'])
初始 DF:
text match
orange 0
apple and lemon 1
lemon and orange 1
这是我需要匹配的单词列表
exactmatch = ['apple', 'lemon']
预期结果:
text match exact words
orange 0 0
apple and lemon 1 'apple','lemon'
lemon and orange 1 'lemon'
这是我尝试过的:
# for some rows it gives me words I want,
#and for some it gives me parts of the word
#regex attempt 1, gives me partial matches (syllables or single letters)
pattern1 = '|'.join(exactmatch)
df['contains'] = df['text'].str.extract("(" + "|".join(exactmatch)
+")", expand=False)
#regex attempt 2 - this gives me an error - unexpected EOL
df['contains'] = df['text'].str.extractall
("(" + "|".join(exactmatch) +")").unstack().apply(','.join, 1)
#TypeError: ('sequence item 1: expected str instance, float found',
#'occurred at index 2')
#no regex attempt, does not give me matches if the word is in there
lst = list(df['text'])
match = []
for w in lst:
if w in exactmatch:
match.append(w)
break
【问题讨论】:
-
你能发布你的预期输出吗?
-
@harvpan 预期的输出在 df - 列'exact words'中。现在将编辑问题
标签: python regex pandas dataframe