0

I am trying to determine if two variables are found in the dataframe

table:
Code    index
600.SI  4th Q 2015
500.SI  Full Year
ggr.SI  1st Q 2016

# If variable_code and variable_date is not found in table, print not found
if table['Code'].str.contains(variable_code).any() & table['index'].str.contains(variable_date).any():
    print('found')
else:
    print('not found')

However, it always return me found.

I think my if statement is structured incorrectly to do a bool comparison for two items.

How can this be solved?

Update

Normally, variable_code will be found in table. if variable_code is found in table, check if variable_date is present too.

What I am trying to achieve is, If both of these conditions are not present, print not found.

cs95
  • 379,657
  • 97
  • 704
  • 746
jake wong
  • 4,909
  • 12
  • 42
  • 85
  • Apologies, I was away so could not test the solution / respond. Thank you very much for helping with the answer, i'll give them a shot shortly! :) – jake wong Aug 24 '17 at 15:04

2 Answers2

0

Replace & with and. & is Bitwise AND operator.

Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
  • Thanks for responding so quickly Danil. I have tried that, but it still does not work. It still prints `found`. Just to add, `variable_code` will normally be found in the `table`, but if `variable_code` is found, `and` `variable_date` is not found, then print `not found`. That is what I am trying to achieve – jake wong Aug 20 '17 at 08:19
0

With str.contains, regex=True by default, so if you're not careful, you won't be matching the right things. If you want to check for equality rather than containment, use the == operator, like this:

if not table[(table['Code'] == variable_code) 
             & (table['index'] == variable_date)].empty: # https://stackoverflow.com/a/45780191/4909087
    print('Found')
else:
    print('Not found')
cs95
  • 379,657
  • 97
  • 704
  • 746