Check if string is in a pandas dataframe
我想看看在我的数据框架中的特定列中是否存在特定的字符串。
我得到了错误
ValueError: The truth value of a Series is ambiguous. Use a.empty,
a.bool(), a.item(), a.any() or a.all().
1 2 3 4 5 6 7 8 | 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" |
因此,您可以使用
1 2 3 | mel_count=a['Names'].str.contains('Mel').sum() if mel_count>0: print ("There are {m} Mels".format(m=mel_count)) |
或者
1 2 | if a['Names'].str.contains('Mel').any(): print ("Mel is there") |
你应该使用
1 2 3 4 5 6 7 | 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 |
1 2 3 4 5 6 7 8 | In [100]: a['Names'].str.contains('Mel') Out[100]: 0 False 1 False 2 False 3 False 4 True Name: Names, dtype: bool |