2015-06-19 50 views
14

我想查看某個特定的字符串是否存在於我的數據框中的特定列中。檢查字符串是否在熊貓數據框中

,我發現了錯誤

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" 

回答

19

a['Names'].str.contains('Mel')將返回大小的布爾值的指標向量len(BabyDataSet)

因此,您可以使用

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

或者any(),如果你不在乎多少記錄匹配您的查詢

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

您應該使用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')爲您提供了一系列的布爾值

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

誰你是嗎,@JohnGalt? –