0

I've written a fuction with lots of ELIF and OR statements. Code is working, but result is not what i'm expacting to get - absolutly the same values in DF table i'm cooperating with. What am I doing wrong?

def some_func(x):
   if x == "aaaa" or "bbb" or "ccc" or "zzz":
    return 1
   elif x == "ddd" or "eee" or "fff" or "ggg":
      return 2
   elif x == "hhh" or "ppp" or "nnn" or "mmm":
      return 3
   else:
      return 0 

df.TABLE_name = df.TABLE_name.apply(some_func).astype('int64')
df['TABLE_name'].value_counts()

Out: 1 38133

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Nigel
  • 13
  • 3

2 Answers2

0

Although your intuition is correct, the way your code is currently set up, it is not executing how you want.

Writing:

if x == "hello" or "world" does not check to see if x is equal to hello or equal to world. It checks to see if x is equal to hello and automatically returns true, because it essentially is evaluating if("hello"), which would always return true

Your code isn't working properly because your syntax is wrong. Consider making these changes:

def some_func(x):
   if x == "aaaa" or x == "bbb" or x == "ccc" or x == "zzz":
    return 1
   elif x == "ddd" or x == "eee" or x == "fff" or x == "ggg":
      return 2
   elif x == "hhh" or x == "ppp" or x == "nnn" or x == "mmm":
      return 3
   else:
      return 0 
artemis
  • 6,857
  • 11
  • 46
  • 99
0

Rather than doing multiple O(n) comparisons in each if/elif statement consider using a set for single O(1) comparison instead:

def some_func(x):
    if x in {"aaaa", "bbb", "ccc", "zzz"}:
        return 1
    elif x in {"ddd", "eee", "fff", "ggg"}:
        return 2
    elif x in {"hhh", "ppp", "nnn", "mmm"}:
        return 3
    else:
        return 0
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40