我有一个包含 2 列的 CSV 文件:“Title
”、“Ingredients
”和单词列表:[“peanut butter, chocolate chip, pizza, ice cream, sweet potato, crock pot, steak, pan cake, green beans, cream cheese, pork chop
”]。我需要在“Ingredients
”列中查找这些单词,如果在其中找到列表中的任何单词,它们将被添加到该特定行中的新列:“Categories
”。例如:如果“Ingredients
”= ice cream, pizza, chicken
;然后“Categories
”= ice cream, pizza
(因为 chicken
不在我们的列表中)。我是 Pandas 的初学者,在互联网上搜索了可能的解决方案,但没有成功。我也尝试过df[df[''].str.contains())]
但我无法让它发挥作用。任何帮助,将不胜感激。
最佳答案
重症监护病房
数据
df2=pd.DataFrame({'Ingredients':['ice cream, pizza, chicken', 'peanut butter, chocolate chip, beey, pizza']})
df2
连接列表l中的所有字符串
l=['peanut butter', 'chocolate chip', 'pizza', 'ice cream', 'sweet potato', 'crock pot', 'steak', 'pan' 'cake', 'green' 'beans', 'cream' 'cheese', 'pork' 'chop']
s='|'.join(l)
s
应用 str.findall
df2['Categories']=df2.Ingredients.str.findall(s)
df2
如果需要可以添加 N/A
df2['Categories']=np.where(df2.Ingredients.str.match(s),df2['Categories'],'N/A')
df2
结果
发表评论后重新运行
关于python-3.x - 在 Pandas Dataframe 列中查找某些单词,如果找到,将它们添加到新列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61456191/