vendredi 30 août 2019

UnboundLocalError: local variable 'y' referenced before assignment in Pandas

I am trying to apply one funtion to a column but i am getting the error

Name    weight
Person1 30
Person2 70

My code is below

def classify(x):
    if 0 <= x < 20:
        y = "0 to 20%"
    if 20 < x < 40:
        y = "20 to 40%"
    if 40 < x < 60:
        y = "40 to 60%"
    if 60 < x < 80:
        y = "60 to 80%"
    if 80 < x <= 100:
        y = "80 to 100%"
    return ( y)

df['Target'] = df['weight'].apply(lambda x: classify(x)) throwing the Local bound error

If I use print instead of return I am able to see the outputs

Expected out

    Name    weight  Target
    Person1     30  20 to 40
    Person2     70  60 to 80

Aucun commentaire:

Enregistrer un commentaire