Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python pandas using an If..elif..else with multiple or

I’m looking to use something simialr to .isin instead of multiple or’s in this code:

def func(row):
    if row['Office'] == 'USA' or row['Office'] == 'UK' or row['Office'] == 'Aus' or row['Office'] == 'Can':   
        return 1        
    else:
        return 2
    
office_data['Area'] = office_data.apply(func, axis=1)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If using Python +3.10, you can use the match - case in replace of IF statements:

def func(row):
  match row['Office']:
    case 'USA':
      return 1

    case 'UK':
      return 1

    case 'Aus':
      return 1

    case 'Can':
      return 1

    case _:
      return 0

For your case, I would recommend using a dictionary with the possible candidates, like this:

def func(row):
  valid_options = ['USA', 'UK', 'Aus', 'Can']
  if row['Office'] in valid_options: return 1
  return 0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading