2015-06-19 18 views
14

Tôi muốn xem liệu một chuỗi cụ thể có tồn tại trong một cột cụ thể trong khung dữ liệu của tôi hay không.Kiểm tra xem chuỗi có nằm trong khung dữ liệu gấu trúc không

Tôi nhận được lỗi

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" 

Trả lời

19

a['Names'].str.contains('Mel') sẽ trả về một véc tơ chỉ số về giá trị boolean kích thước len(BabyDataSet)

Vì vậy, bạn có thể sử dụng

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

Hoặc any(), nếu bạn không quan tâm có bao nhiêu hồ sơ phù hợp với truy vấn của bạn

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

Bạn nên sử dụng 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') cung cấp cho bạn một loạt các giá trị 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

Ai là bạn, @JohnGalt? –

Các vấn đề liên quan