2015-06-19 18 views
14

Chciałbym sprawdzić, czy konkretny ciąg istnieje w określonej kolumnie w mojej ramce danych.Sprawdź, czy ciąg jest w ramce danych pandy

Dostaję błąd

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

import pandas as pd 

BabyDataSet = [('Bob', 968), ('Jessica', 155), ('Mary', 77), ('John', 578), ('Mel', 973)] 

a = pd.DataFrame(data=BabyDataSet, columns=['Names', 'Births']) 

if a['Names'].str.contains('Mel'): 
    print "Mel is there" 

Odpowiedz

19

a['Names'].str.contains('Mel') zwróci wektor wskaźnik logicznych wartości wielkości len(BabyDataSet)

Dlatego można użyć

mel_count=a['Names'].str.contains('Mel').sum() 
if mel_count>0: 
    print ("There are {m} Mels".format(m=mel_count)) 

Or any(), jeśli nie obchodzi ile rekordów spełniających kryteria wyszukiwania

if a['Names'].str.contains('Mel').any(): 
    print ("Mel is there") 
10

należy użyć any()

In [98]: a['Names'].str.contains('Mel').any() 
Out[98]: True 

In [99]: if a['Names'].str.contains('Mel').any(): 
    ....:  print "Mel is there" 
    ....: 
Mel is there 

a['Names'].str.contains('Mel') daje szereg bool wartości

In [100]: a['Names'].str.contains('Mel') 
Out[100]: 
0 False 
1 False 
2 False 
3 False 
4  True 
Name: Names, dtype: bool 
+0

Kto jesteś ty, @JohnGalt? –

Powiązane problemy