mercredi 12 février 2020

Using "If" statements in Python 3 and other rows from other columns to produce value of other column

Regards,

Forgive me if this question appears to be a duplicate, but I couldn't find an answer to existing questions that matches my exact requirements:

I would like to use the row values from other columns to produce the row value of a column. To do this, I have produced a helper function, "f":

def f(row):    

    if row['column1'] == 3:
        val = 0

    if row['column2'] <= 5:
        if row['column3'] <= 4:
            if row['column4'] >= 3:
                val = 3        

    if row['column5'] == 2:
        val = 5 

    if row['column6'] == 0:
        if row['column7'] <= 0:
            if row['column8'] <= -1:
                val = 4

    else:
        val = 9

    return val

I applied my helper function to my dataframe as follows:

df['column12'] = df.apply(f, axis=1)

This produced the error code:

UnboundLocalError: ("local variable 'val' referenced before assignment", 'occurred at index 0')

Where am I going wrong?

Aucun commentaire:

Enregistrer un commentaire