【问题标题】:How do I check if a row contains a certain string from a list of words如何检查一行是否包含单词列表中的某个字符串
【发布时间】:2017-10-12 08:58:18
【问题描述】:
for i in range(len(ingName)):
    x = ingName[i]
    #check if the string contains IngName ignoring uppercase Sub_Seg_Sub_Cat
    df = df_grocery[df_grocery['Sub_Seg_Sub_Cat'].str.contains(str(ingName[i]), case=False)]
    df['IngredientName'] = ingName[i]
    df['IngredientID'] = ingID[i]

    #write it out to a csv
    df.to_csv("ingred11.csv",  mode = 'a', encoding='utf-8', header=None)

检查列中的行是否包含某些单词的最佳方法是什么?我正在使用 str.contains 并且它正在获取子字符串。我想要它检查意大利面酱中是否存在酱汁,而不是意大利面酱中是否存在酱汁,目前这就是它的作用,还有什么方法可以实现吗?

谢谢

【问题讨论】:

  • 嘿@Andy Hayden,谢谢,但如果我输入 s = pd.Series(["cat dog", "dog", "sheep"]) s.isin(["cat" , "dog"]) 但我希望它能够知道它的真实性

标签: python regex string pandas


【解决方案1】:

这就是你所追求的吗?

s = pd.Series(["cat dog", "dog", "sheep"])

# check if 'cat' or 'dog' is present in the Series.
s.apply(lambda x: np.max(np.in1d(np.asarray(x.split()), ['cat', 'dog'])))
Out[785]: 
0     True
1     True
2    False

【讨论】:

  • 当然,谢谢你,我投票给你的答案,但我昨天决定通过另一条路线来处理我正在处理的文件,但我会保存这个,然后再回来,因为我可能很快就会需要它。
【解决方案2】:

你可以使用isin方法:

In [11]: s = pd.Series(["cat", "dog", "sheep"])

In [12]: s.isin(["cat", "dog"])
Out[12]:
0     True
1     True
2    False
dtype: bool

【讨论】:

  • 如果我输入它会显示 false s = pd.Series(["cat dog", "dog", "sheep"]) s.isin(["cat", "dog"] ) 但我希望它能够知道它的真实性
  • @AbifoluwaOni 我不明白你的意思。第一行是 True 因为"cat"["cat", "dog"]...
猜你喜欢
  • 2012-05-20
  • 2015-03-14
  • 1970-01-01
  • 1970-01-01
  • 2021-05-20
  • 2021-07-21
  • 2014-01-25
  • 2017-10-16
  • 1970-01-01
相关资源
最近更新 更多