Python 在pandas中搜索多个字符串,而不预定义要使用的字符串数

Python 在pandas中搜索多个字符串,而不预定义要使用的字符串数,python,pandas,Python,Pandas,我想知道是否有一个更一般的方法来做下面的事情?我想知道是否有一种方法可以创建st函数,以便搜索非预定义数量的字符串 例如,能够创建一个通用的st函数,然后键入st('Governor','Virginia','Google) 这是我当前的函数,但它预定义了两个可以使用的单词。(df是一个数据帧) 您可以使用np.logical\u和.reduce: import pandas as pd import numpy as np def search(df, *words): #1 """

我想知道是否有一个更一般的方法来做下面的事情?我想知道是否有一种方法可以创建st函数,以便搜索非预定义数量的字符串

例如,能够创建一个通用的st函数,然后键入st('Governor','Virginia','Google)

这是我当前的函数,但它预定义了两个可以使用的单词。(df是一个数据帧)


您可以使用
np.logical\u和.reduce

import pandas as pd
import numpy as np
def search(df, *words):  #1
    """
    Return a sub-DataFrame of those rows whose Name column match all the words.
    """
    return df[np.logical_and.reduce([df['Name'].str.contains(word) for word in words])]   # 2


df = pd.DataFrame({'Name':['Virginia Google Governor',
                           'Governor Virginia',
                           'Governor Virginia Google']})
print(search(df, 'Governor', 'Virginia', 'Google'))
印刷品

                       Name
0  Virginia Google Governor
2  Governor Virginia Google

  • def search(df,*words)
    中的
    *
    允许
    search
    接受 无限数量的位置参数。它将收集所有的数据 参数(在第一个参数之后),并将它们放在名为
    单词的列表中
  • 相当于
    X&Y&Z
    。信息技术 但是,允许您处理任意长的列表

  • str.contains
    可以接受正则表达式。因此,您可以使用
    '|'。连接(单词)
    作为模式;为了安全起见,请同时映射到
    re.escape

    >>> df
                     Name
    0                Test
    1            Virginia
    2              Google
    3  Google in Virginia
    4               Apple
    
    [5 rows x 1 columns]
    >>> words = ['Governor', 'Virginia', 'Google']
    
    “|”。join(map(re.escape,words))
    将是搜索模式:

    >>> import re
    >>> pat = '|'.join(map(re.escape, words))
    >>> df.Name.str.contains(pat)
    0    False
    1     True
    2     True
    3     True
    4    False
    Name: Name, dtype: bool
    

    这很有帮助!我喜欢这两个答案,但我选择了下面的一个,因为它允许你输入任意长的带有*单词的答案列表,我不知道。我也不知道正则表达式在str.contains中工作,所以这非常有用。是否可以在多个字段上运行contains而不使用and运算符?pseudo:
    'df['Name','AnotherField'].str.contains(pattern)
    对不起,“OR”有等价物吗?如果我还想混合使用or和搜索,我会怎么做?有两种方法来处理
    。如behzad.nouri所示,您可以将正则表达式模式与
    组合,也可以使用
    np.logical\u或.reduce
    。但是,允许用户输入regex(可能包含
    )并使用
    search
    将regex与
    np.logical\u和.reduce组合起来可能是最简单的。
    
    >>> import re
    >>> pat = '|'.join(map(re.escape, words))
    >>> df.Name.str.contains(pat)
    0    False
    1     True
    2     True
    3     True
    4    False
    Name: Name, dtype: bool