2016-05-03 17 views
7

df (Panda DataFame) ma trzy wiersze.pandasowa ramka danych str.contains() I operacja

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

df.col_name.str.contains ("jabłko | banan")

złapie wszystkie wiersze:

"jabłko jest pyszne", "Banan jest pyszne", "jabłka i banany są pyszne".

Jak zastosować operator AND w metodzie str.contains, aby pobierał tylko łańcuchy z dwoma bananami: jabłko &?

"apple and banana both are delicious" 

Chciałbym złapać ciągi że zawiera 10-20 różne słowa (winogrono, arbuz, jagody, pomarańczowy, ... etc.)

Odpowiedz

6

Można to zrobić w następujący sposób:

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

można również zrobić to w stylu regex wyrażenie:

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

można wtedy budować swoją listę słów do regex ciąg tak:

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

odda:

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

Następnie można zrobić dynamicznie swoje rzeczy.

0

Spróbuj regex

apple.*banana|banana.*apple 

Code jest:

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')] 

Wyjście

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

jeśli chcesz złapać w minimalnej conajmniej dwa słowa w zdaniu, może to zadziała (biorąc końcówkę z @Alexander):

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

wyjściowa:

        col 
2 apple and banana both are delicious 

jeśli masz więcej niż dwa słowa zatrzask, który jest oddzielony przecinkami „” niż dodać do connector_list i modyfikację drugiego warunku z każdego dowolnego wyjścia

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

:

         col 
2  apple and banana both are delicious 
3 orange,banana and apple all are delicious 
Powiązane problemy