2013-07-31 21 views
23

如果我有這樣的檢查,如果字符串中的大熊貓據幀列在名單

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") 

frame['b']輸出:

True 
False 
True 

如果我決定做一個列表

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

我怎麼會檢查該行包含在列表中的某個單詞?

回答

45

str.contains方法接受一個正則表達式模式:

In [11]: pattern = '|'.join(mylist) 

In [12]: pattern 
Out[12]: 'dog|cat|fish' 

In [13]: frame.a.str.contains(pattern) 
Out[13]: 
0  True 
1 False 
2  True 
Name: a, dtype: bool 
+0

這顯著加快了我在做什麼。有什麼辦法可以返回子模式(比如說* dog *)而不是真正的錯誤嗎? – zelusp

+1

想通了:返回匹配的模式使用'frame.a.str.extract(pattern)' – zelusp