2016-05-03 11 views
7

df (Pandas Dataframe) hat drei Zeilen.Pandas Datenrahmen str.contains() UND-Operation

some_col_name 
"apple is delicious" 
"banana is delicious" 
"apple and banana both are delicious" 

df.col_name.str.contains ("Apfel | Banane")

werden alle Zeilen fangen:

"Apfel köstlich", "Banane ist köstlich" "Apfel und Banane sind beide köstlich".

Wie kann ich AND-Operator auf str.contains-Methode anwenden, so dass es nur Strings, die BEIDE Apfel enthalten & Banane?

"apple and banana both are delicious" 

Ich möchte Saiten greifen, die 10 bis 20 verschiedene Wörter enthält (Traube, Wassermelone, Beeren, orange, ..., etc.)

Antwort

6

Sie können das tun, wie folgt:

df[(df['col_name'].str.contains('apple')) & (df['col_name'].str.contains('banana'))] 
0

Sie können es auch tun, in regulären Ausdruck Stil:

df[df['col_name'].str.contains(r'^(?=.*apple)(?=.*banana)')] 

Sie können dann Ihre Liste von Wörtern in eine Regex String bauen so wie:

base = r'^{}' 
expr = '(?=.*{})' 
words = ['apple', 'banana', 'cat'] # example 
base.format(''.join(expr.format(w) for w in words)) 

machen wird:

'^(?=.*apple)(?=.*banana)(?=.*cat)' 

Dann können Sie Ihre Sachen dynamisch tun.

0

Versuchen Sie, diese Regex

apple.*banana|banana.*apple 

-Code ist:

import pandas as pd 

df = pd.DataFrame([[1,"apple is delicious"],[2,"banana is delicious"],[3,"apple and banana both are delicious"]],columns=('ID','String_Col')) 

print df[df['String_Col'].str.contains(r'apple.*banana|banana.*apple')] 

Ausgabe

ID       String_Col 
2 3 apple and banana both are delicious 
8
df = pd.DataFrame({'col': ["apple is delicious", 
          "banana is delicious", 
          "apple and banana both are delicious"]}) 

targets = ['apple', 'banana'] 

# Any word from `targets` are present in sentence. 
>>> df.col.apply(lambda sentence: any(word in sentence for word in targets)) 
0 True 
1 True 
2 True 
Name: col, dtype: bool 

# All words from `targets` are present in sentence. 
>>> df.col.apply(lambda sentence: all(word in sentence for word in targets)) 
0 False 
1 False 
2  True 
Name: col, dtype: bool 
1

, wenn Sie in der minimalen atleast zwei Wörter im Satz fangen wollen, vielleicht wird dies funktionieren (die Spitze von @Alexander nehmen):

target=['apple','banana','grapes','orange'] 
connector_list=['and'] 
df[df.col.apply(lambda sentence: (any(word in sentence for word in target)) & (all(connector in sentence for connector in connector_list)))] 

Ausgang:

        col 
2 apple and banana both are delicious 

, wenn Sie mehr als zwei Worte zu fangen, die durch Kommata getrennt sind, ‚‘, als es zu dem connector_list hinzufügen und die zweite Bedingung von allen zu jedem

df[df.col.apply(lambda sentence: (any(word in sentence for word in target)) & (any(connector in sentence for connector in connector_list)))] 

Ausgang modifiziert:

         col 
2  apple and banana both are delicious 
3 orange,banana and apple all are delicious