2014-03-25 41 views
10

我想知道是否有更一般的方法來執行下面的操作?我想知道是否有一種方法來創建st函數,以便我可以搜索非預定義數量的字符串?在沒有預定義字符串數的情況下搜索熊貓中的多個字符串

因此,舉例來說,能夠創造一個廣義ST功能,然後鍵入ST(「總督」,「弗吉尼亞」,「谷歌)

這裏是我當前的功能,但它預定義了兩句話,你可以使用。 (DF是大熊貓數據幀)

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) 

回答

11

你可以使用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 

  1. def search(df, *words)*允許search接受一個 無限數量的位置參數。它將收集所有參數(在第一個之後)並將它們放在名爲words的列表中。
  2. np.logical_and.reduce([X,Y,Z])相當於X & Y & Z。但是,它可以讓你處理一個任意長的列表。
+1

遺憾是有「或」等同?如果我也想混入或和搜索,我該怎麼做? – user3314418

+0

有兩種方法來處理'OR'。您可以將正則表達式模式與'|'結合使用,如behzad.nouri所示,或者您可以使用'np.logical_or.reduce'。然而,允許用戶輸入正則表達式(可能包含'|'),並使用'search'將正則表達式與'np.logical_and.reduce'結合起來可能是最簡單的。 – unutbu

11

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))將是搜索模式:

>>> 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 
+0

這很有幫助!我喜歡這兩個答案,但我選擇了下面的答案,因爲它允許您輸入一個任意長的答案列表,其中包含*字,我不知道。我也不知道正則表達式在str.contains中工作,所以這非常有用。 – user3314418

+0

是否可以在不使用和運算符的情況下在多個字段上運行包含? pseudo:''df ['Name','AnotherField']。str.contains(pattern)' – radtek