首页 文章

检查字符串是否在pandas数据帧中

提问于
浏览
25

我想看看我的数据帧中的特定列中是否存在特定字符串 .

我收到了错误

ValueError:系列的真值是不明确的 . 使用a.empty,a.bool(),a.item(),a.any()或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"

2 回答

  • 37

    你应该使用 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') 为您提供一系列bool值

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

    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")
    

相关问题