2015-06-19 14 views
14

Vorrei vedere se esiste una stringa particolare in una particolare colonna all'interno del mio dataframe.Controlla se la stringa è in un dataframe panda

sto ottenendo l'errore

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" 

risposta

19

a['Names'].str.contains('Mel') restituirà un indicatore vettore di valori booleani di dimensioni len(BabyDataSet)

Pertanto, è possibile utilizzare

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

O any(), se non vi interessa quanti record corrisponde alle Sue esigenze

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

Si dovrebbe usare 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') ti dà una serie di valori bool

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

Chi sei tu, @JohnGalt? –

Problemi correlati