Check if string is in a pandas dataframe

前端 未结 7 2016
北荒
北荒 2020-11-28 06:38

I would like to see if a particular string exists in a particular column within my dataframe.

I\'m getting the error

ValueError: The truth v

相关标签:
7条回答
  • 2020-11-28 06:48

    it seems that the OP meant to find out whether the string 'Mel' exists in a particular column, not contained in a column, therefore the use of contains is not needed, and is not efficient. A simple equals-to is enough:

    (a['Names']=='Mel').any()
    
    0 讨论(0)
  • 2020-11-28 06:50

    Pandas seem to be recommending df.to_numpy since the other methods still raise a FutureWarning: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html#pandas.DataFrame.to_numpy

    So, an alternative that would work int this case is:

    b=a['Names']
    c = b.to_numpy().tolist()
    if 'Mel' in c:
         print("Mel is in the dataframe column Names")
    
    0 讨论(0)
  • 2020-11-28 06:58

    a['Names'].str.contains('Mel') will return an indicator vector of boolean values of size len(BabyDataSet)

    Therefore, you can use

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

    Or any(), if you don't care how many records match your query

    if a['Names'].str.contains('Mel').any():
        print ("Mel is there")
    
    0 讨论(0)
  • 2020-11-28 07:02

    You should use 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') gives you a series of bool values

    In [100]: a['Names'].str.contains('Mel')
    Out[100]:
    0    False
    1    False
    2    False
    3    False
    4     True
    Name: Names, dtype: bool
    
    0 讨论(0)
  • 2020-11-28 07:06

    You should check the value of your line of code like adding checking length of it.

    if(len(a['Names'].str.contains('Mel'))>0):
        print("Name Present")
    
    0 讨论(0)
  • 2020-11-28 07:11

    If there is any chance that you will need to search for empty strings,

        a['Names'].str.contains('') 
    

    will NOT work, as it will always return True.

    Instead, use

        if '' in a["Names"].values
    

    to accurately reflect whether or not a string is in a Series, including the edge case of searching for an empty string.

    0 讨论(0)
提交回复
热议问题