Home > Enterprise >  Is this syntax for an If Elif Else statement correct? There is an error for my variable name
Is this syntax for an If Elif Else statement correct? There is an error for my variable name

Time:04-22

I am trying to set age and salary date into three categories and do no know what is messing up.

subset['AGE_Range'] = subset['AGE'].map(lambda x:'old' if x > 29 'mid' elif 25 < x < 30 else 'young')
subset['AVG_Salary_Range'] = subset['AVG_SALARY'].map(lambda x:'high' if x > 15000000 'med' elif 6000000 < x < 15000000 else 'low')

Here is the error that I receive.

File "/var/folders/hx/q1y8qq5n4fgc2fl8y1zfbhlw0000gn/T/ipykernel_15491/1445428960.py", line 1
    subset['AGE_Range'] = subset['AGE'].map(lambda x:'old' if x > 29 'mid' elif 25 < x < 30 else 'young')
                                                                     ^
SyntaxError: invalid syntax

CodePudding user response:

No, your if statement is not correct. The inline if operator doesn't have an elif option. So, don't use a lambda:

def agerange(x):
    if x > 29:
        return 'old'
    elif x > 25:
        return 'mid'
    else:
        return 'young'

def salaries(x):
    if x > 15000000:
        return 'high'
    elif x > 6000000:
        return 'med'
    else:
        return 'low'
...
subset['AGE_Range'] = subset['AGE'].map(agerange)
subset['AVG_Salary_Range'] = subset['AVG_SALARY'].map(salaries)

CodePudding user response:

1 : if you wanna use elif you can do somting like tihs

map(lambda x:'old' if x > 29  else 'mid' if 25 < x < 30 else 'young')

2: You need two arguments for the map Function

3: you cant pass int as argument for map Function

Maybe this will help

  • Related