2014-01-10 52 views

回答

24

您可以使用波浪號~翻轉布爾值:

>>> df = pd.DataFrame({"A": ["Hello", "this", "World", "apple"]}) 
>>> df.A.str.contains("Hello|World") 
0  True 
1 False 
2  True 
3 False 
Name: A, dtype: bool 
>>> ~df.A.str.contains("Hello|World") 
0 False 
1  True 
2 False 
3  True 
Name: A, dtype: bool 
>>> df[~df.A.str.contains("Hello|World")] 
     A 
1 this 
3 apple 

[2 rows x 1 columns] 

這是否是最有效的方式,我不知道;你不得不對其他選項進行計時。有時候使用正則表達式比像df[~(df.A.str.contains("Hello") | (df.A.str.contains("World")))]這樣的東西慢,但我很難猜測交叉是在哪裏。

+0

比複雜的負面查找測試好得多。然而,沒有大熊貓的經驗,所以我不知道什麼是更快的方法。 –

+1

正則環視測試花費了更長的時間(大約30s vs 20s),並且這兩種方法顯然有稍微不同的結果(3663K結果vs 3504K--來自3G原始 - 沒有看到具體細節)。 – Xodarap777

+0

@DSM我已經多次看到這個'〜'符號,特別是在JavaScript中。在Python中沒有見過。這到底意味着什麼? – estebanpdl

7

.contains()方法使用正則表達式,所以你可以使用一個negative lookahead test來確定某個單詞是包含:

df['A'].str.contains(r'^(?:(?!Hello|World).)*$') 

這種表達的哪裏話HelloWorld任何字符串相匹配發現在字符串的任何地方。

演示:

>>> df = pd.DataFrame({"A": ["Hello", "this", "World", "apple"]}) 
>>> df['A'].str.contains(r'^(?:(?!Hello|World).)*$') 
0 False 
1  True 
2 False 
3  True 
Name: A, dtype: bool 
>>> df[df['A'].str.contains(r'^(?:(?!Hello|World).)*$')] 
     A 
1 this 
3 apple 
+0

我得到了'C:\ Python27 \ lib \ site-packages \ pandas \ core \ strings.py:176:UserWarning:這個模式有匹配組。要真正獲得組,請使用str.extract.'。 – Xodarap777

+1

使組未捕獲。 –