在 Pandas 中搜索多个字符串而不预先定义要使用的字符串数量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22623977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:51:05  来源:igfitidea点击:

Searching Multiple Strings in pandas without predefining number of strings to use

pythonpandas

提问by user3314418

I'm wondering if there's a more general way to do the below? I'm wondering if there's a way to create the st function so that I can search a non-predefined number of strings?

我想知道是否有更通用的方法来执行以下操作?我想知道是否有办法创建 st 函数,以便我可以搜索非预定义数量的字符串?

So for instance, being able to create a generalized st function, and then type st('Governor', 'Virginia', 'Google)

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

here's my current function, but it predefines two words you can use. (df is a pandas DataFrame)

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

def search(word1, word2, word3 df):
    """
    allows you to search an intersection of three terms
    """
    return df[df.Name.str.contains(word1) & df.Name.str.contains(word2) & df.Name.str.contains(word3)]

st('Governor', 'Virginia', newauthdf)

回答by unutbu

You could use np.logical_and.reduce:

你可以使用np.logical_and.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'))

prints

印刷

                       Name
0  Virginia Google Governor
2  Governor Virginia Google


  1. The *in def search(df, *words)allows searchto accept an unlimited number of positional arguments. It will collect all the arguments (after the first) and place them in a list called words.
  2. np.logical_and.reduce([X,Y,Z])is equivalent to X & Y & Z. It allows you to handle an arbitrarily long list, however.
  1. *def search(df, *words)允许search接受的位置参数的数量不受限制。它将收集所有参数(在第一个之后)并将它们放在一个名为words.
  2. np.logical_and.reduce([X,Y,Z])等价于X & Y & Z. 但是,它允许您处理任意长的列表。

回答by behzad.nouri

str.containscan take regex. so you can use '|'.join(words)as the pattern; to be safe map to re.escapeas well:

str.contains可以带正则表达式。所以你可以'|'.join(words)用作模式;也是安全的映射到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))would be the search pattern:

'|'.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