python-3.x - 在 Pandas Dataframe 列中查找某些单词,如果找到,将它们添加到新列中

标签 python-3.x pandas

我有一个包含 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

结果

enter image description here

发表评论后重新运行

enter image description here

关于python-3.x - 在 Pandas Dataframe 列中查找某些单词,如果找到,将它们添加到新列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61456191/

相关文章:

python - 将函数调用作为函数参数传递

python - 如何让 SublimeText 支持 Python 3 的注解?

python - 如何制作高质量的 matplotlib 动画并避免模糊的文本/线条渲染?

python - 在 Pandas DataFrame 中重新定义索引值

python - Pandas Groupby 应用函数来计算大于零的值

python - Pandas 按值分组并合并行

输入期间的 Python 操作()

python-3.x - 从集合列表中查找元素数量最少的集合

python - 标记接下来 X 行的合格行

python - 将 Pandas DateTimeIndex 转换为 YYYYMMDD 整数?