在pandas中搜索多个字符串而不预定义字符串数量
我在想有没有更通用的方法来实现下面的功能?我想知道有没有办法创建一个 st 函数,这样我就可以搜索任意数量的字符串,而不是事先定义好的数量。
举个例子,我希望能够创建一个通用的 st 函数,然后输入 st('Governor', 'Virginia', 'Google') 这样的内容。
这是我现在的函数,但它只允许使用两个预先定义的单词。(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)
2 个回答
15
str.contains
可以使用正则表达式(regex)。所以你可以用 '|'.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))
就是要用的搜索模式:
>>> 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
17
你可以使用 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'))
输出结果是
Name
0 Virginia Google Governor
2 Governor Virginia Google
*
在def search(df, *words)
中的作用是让search
可以接收任意数量的位置参数。它会把所有参数(除了第一个)收集起来,放到一个叫words
的列表里。- np.logical_and.reduce([X,Y,Z]) 的意思和
X & Y & Z
是一样的。不过,它可以处理任意长度的列表。