2014-12-04 158 views
3

的列出了一系列給定一個簡單的熊貓系列包含某些字符串可以由一個以上的一句話:使用熊貓字符串的方法「包含」在包含字符串

In: 
import pandas as pd 
s = pd.Series(['This is a long text. It has multiple sentences.','Do you see? More than one sentence!','This one has only one sentence though.']) 

Out: 
0 This is a long text. It has multiple sentences. 
1    Do you see? More than one sentence! 
2    This one has only one sentence though. 
dtype: object 

我用熊貓字符串方法split和正則表達式模式將每行分成單個句子(這會產生不必要的空列表元素 - 關於如何改進正則表達式的任何建議?)。

In: 
s = s.str.split(r'([A-Z][^\.!?]*[\.!?])') 

Out: 
0 [, This is a long text., , It has multiple se... 
1  [, Do you see?, , More than one sentence!, ] 
2   [, This one has only one sentence though., ] 
dtype: object 

這將每行轉換爲字符串列表,每個元素都包含一個句子。

現在,我的目標是使用字符串方法contains單獨檢查每行中的每個元素以匹配特定的正則表達式模式,並相應地創建一個新的Series,它存儲返回的布爾值,每個布爾值指示正則表達式匹配至少有一個列表元素。

我希望是這樣的:

In: 
s.str.contains('you') 

Out: 
0 False 
1 True 
2 False 

< - 0行不包含任何元素'you',但第1行呢,而第2行沒有。

但是,這樣做上面的時候,回報是

0 NaN 
1 NaN 
2 NaN 
dtype: float64 

我也嘗試了列表中理解不工作:如何可以做到這一點

result = [[x.str.contains('you') for x in y] for y in s] 
AttributeError: 'str' object has no attribute 'str' 

有什麼建議?

回答

2

你可以使用Python find()方法

>>> s.apply(lambda x : any((i for i in x if i.find('you') >= 0))) 
0 False 
1  True 
2 False 
dtype: bool 

我猜s.str.contains('you')不工作,因爲你的一系列元素不是字符串,但名單。但你也可以這樣做:

>>> s.apply(lambda x: any(pd.Series(x).str.contains('you'))) 
0 False 
1  True 
2 False 
+0

Hooray,謝謝!我比較喜歡後者,因爲'contains'可以讓你使用正則表達式進行搜索,而'find'需要一個字符串。然而,在簡單的情況下,當不需要正則表達式時,我猜可能會更快。 – Dirk 2014-12-04 17:53:08

+1

@Dirk,以防萬一 - 您可以使用're'模塊通過regexp查找 - https://docs.python.org/2/library/re.html#module-re – 2014-12-04 18:05:50