Search code examples
python-3.xpandasif-statementstring-comparison

How to compare string value by index and column and apply AND OR logic within dataframe?


I have a dataframe that looks like this:

   col1
0  ofcourse
1  I love the service

The dataframe could also have this value for row 1:

   col1
0  ofcourse
1  I hate the service

I want to compare the value of the strings by row and column and be able to check for one of two values in row1.

I want to create this logic:

if df.col1.loc[[0]] =='Of course!' and (df.col1.loc[[1]]=='I love the service' or df.col1.loc[[1]]=='I hate the service'):
    print('good')

When I run the logic above I get error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

What am I doing wrong?


Solution

  • You should remove the []

    df.col1.loc[0] =='Of course!' and (df.col1.loc[1]=='I love the service' or df.col1.loc[1]=='I hate the service')
    

    Why it happen :

    df.loc[[0]] will return the DataFrame, Since that is DataFrame when you did condition here, it will return the DataFrame, which will raise the errors

    and

    df.loc[0] will return the Series


    More Info

    type(df.loc[[0]])
    <class 'pandas.core.frame.DataFrame'>
    type(df.loc[0])
    <class 'pandas.core.series.Series'>