我有一个字符串列表和一个字典。例如:
list = ["apple fell on Newton", "lemon is yellow","grass is greener"]
dict = {"apple" : "fruits", "lemon" : "vegetable"}
任务是将列表中的每个字符串与字典的关键字进行匹配。如果匹配,则返回键的值。
当前,我正在使用这种方法,这非常耗时。有人可以用任何有效的方法帮助我吗?
lmb_extract_type = (lambda post: list(filter(None, set(dict.get(w)[0] if w in post.lower().split() else None for w in dict))))
df['type'] = df[list].apply(lmb_extract_type)
它是单列,在数据帧的每一行中都有一个字符串(例如:“ apple on Newton”)。对于每一行,我必须将其与字典中的键进行匹配,并返回相应键的值
列表中的元素数量大约为40-50百万,因此,这需要花费大量时间
IIUC根据您的注释,可以使用str.extract
和轻松解决此问题series.replace
,这两个都是向量化函数,没有任何循环。
l = ["apple fell on Newton", "lemon is yellow","grass is greener"]
d = {"apple" : "fruits", "lemon" : "vegetable"}
df = pd.DataFrame(l, columns=['sentences']) #Single column dataframe to demonstrate.
pattern = '('+'|'.join(d.keys())+')' #Regular expression pattern
df['type'] = df.sentences.str.extract(pattern).replace(d)
print(df)
sentences type
0 apple fell on Newton fruits
1 lemon is yellow vegetable
2 grass is greener NaN
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句