当前位置: 首页 > 知识库问答 >
问题:

检查Pandas DataFrame列中的字符串是否在字符串列表中

严曜文
2023-03-14

如果我有这样一个框架

frame = pd.DataFrame({
    "a": ["the cat is blue", "the sky is green", "the dog is black"]
})

我想检查这些行中是否有包含某个单词的行,我必须这样做。

frame["b"] = (
   frame.a.str.contains("dog") |
   frame.a.str.contains("cat") |
   frame.a.str.contains("fish")
)

帧[“b”]输出:

0     True
1    False
2     True
Name: b, dtype: bool

如果我决定列一个清单:

mylist = ["dog", "cat", "fish"]

如何检查行是否包含列表中的某个单词?

共有3个答案

刘松
2023-03-14

在检查了提取字符串的已接受答案的注释之后,也可以尝试这种方法。

frame = pd.DataFrame({'a' : ['the cat is blue', 'the sky is green', 'the dog is black']})

frame
              a
0   the cat is blue
1  the sky is green
2  the dog is black

让我们创建我们的列表,其中包含需要匹配和提取的字符串。

mylist = ['dog', 'cat', 'fish']
pattern = '|'.join(mylist)

现在,让我们创建一个函数,该函数将负责查找和提取子字符串。

import re
def pattern_searcher(search_str:str, search_list:str):

    search_obj = re.search(search_list, search_str)
    if search_obj :
        return_str = search_str[search_obj.start(): search_obj.end()]
    else:
        return_str = 'NA'
    return return_str

我们会把这个功能用在熊猫身上。DataFrame.apply

frame['matched_str'] = frame['a'].apply(lambda x: pattern_searcher(search_str=x, search_list=pattern))

结果:

              a             matched_str
   0   the cat is blue         cat
   1  the sky is green         NA
   2  the dog is black         dog
鞠修雅
2023-03-14

因为这个清单应该有用

print(frame[frame["a"].isin(mylist)])

请参见pandas.DataFrame.isin()

籍辰沛
2023-03-14
frame = pd.DataFrame({'a' : ['the cat is blue', 'the sky is green', 'the dog is black']})

frame
                  a
0   the cat is blue
1  the sky is green
2  the dog is black

str.contains方法接受正则表达式模式:

mylist = ['dog', 'cat', 'fish']
pattern = '|'.join(mylist)

pattern
'dog|cat|fish'

frame.a.str.contains(pattern)
0     True
1    False
2     True
Name: a, dtype: bool

由于支持正则表达式模式,您还可以嵌入标志:

frame = pd.DataFrame({'a' : ['Cat Mr. Nibbles is blue', 'the sky is green', 'the dog is black']})

frame
                     a
0  Cat Mr. Nibbles is blue
1         the sky is green
2         the dog is black

pattern = '|'.join([f'(?i){animal}' for animal in mylist])  # python 3.6+

pattern
'(?i)dog|(?i)cat|(?i)fish'
 
frame.a.str.contains(pattern)
0     True  # Because of the (?i) flag, 'Cat' is also matched to 'cat'
1    False
2     True
 类似资料:
  • 问题内容: 我之前已经找到了这个问题的一些答案,但是对于当前的Python版本似乎已经过时了(或者至少它们对我不起作用)。 我想检查子字符串是否包含在字符串列表中。我只需要布尔结果。 我找到了这个解决方案: 我希望从这段代码中得到一个价值。如果单词是“ der”,则输出应为。 但是,结果是一个生成器函数,我找不到找到该值的方法。 任何想法? 问题答案: 您可以导入从的情况下,它是由一些其他的替代:

  • 问题内容: 如果我有这样的框架 我想检查这些行中是否包含某个单词,我只需要这样做。 输出: 如果我决定列出一个清单 如何检查列表中的行是否包含某个单词? 问题答案: 该方法接受正则表达式模式: 由于支持正则表达式模式,因此您还可以嵌入标志:

  • 考虑以下键(under_score)和字段(lowerCamel): 我正在Java中寻找一种有效的方法来检查是否在中,我希望以下返回: 我的代码: 我可以用下划线替换所有小写,但我正在寻找更有效的方法。

  • 问题内容: 如何检查是否是那里的? 我想分配给是否有结果,否则。 我当前的代码是: 问题答案:

  • 问题内容: 如何检查字符串中是否包含字符列表,例如“ ABCDEFGH”,如何检查字符串中是否有字符列表。 问题答案: 在Java中使用正则表达式检查在Java中使用 正则表达式 例如:

  • 在python中,如何检查字符串是否是字符串列表中的元素? 我正在处理的示例数据是: 那么为什么下面代码的结果是"False":