0
votes

I want to apply this function on the following columns but I could not.

def damage(a,b):
  l=5
  if (a==b+0.3) or ((a>=1.5* b) and (a<=1.9 * b)):
    l=1
  elif  (a>=2* b) and (a<=2.9 * b) :
    l=2
  elif   (a>=4) or (a>= 3* b):
    l=3
  elif (a==b) or (a<=b+0.3)  or (a<= 1.5 *b):
    l=0
  return l

df['1st_day_damage'] =df[df['Cr-1'],df['Cr']].apply(damage)
1
Please provide a sample input (as text) and the matching expected output. Also provide details on how your current approach does not workmozway

1 Answers

0
votes

It's better to use vectorized code. apply is slow.

Coding in the blind since you didn't provide any example:

a = df['Cr-1']
b = df['Cr']

df['1st_day_damage'] = np.select(
    [
        (a == b + 0.3) | ((1.5 * b <= a) & (a <= 1.9 * b)),
        (2 * b <= a) & (a <= 2.9 * b),
        (a >= 4) | (a >= 3 * b),
        (a == b) | (a <= b + 0.3) | (a <= 1.5 * b)
    ],
    [
        1,
        2,
        3,
        0
    ],
    default=5
)