vendredi 12 avril 2019

Adding Null values to a pandas dataframe using a if-elif statement

I've tried the following site for the answer to no success:

Adding null values to a pandas dataframe

I need to add null values through a python function.

from numpy import nan

def f(row):
    if row['model'] == 'C5' and row['x'] <= 600:
        val = 600
    elif row['model'] == 'C5' and row['x'] > 600 and row['score'] <= 675:
        val = 675
    elif row['model'] == 'C5' and row['x'] > 675 and row['score'] <= 710:
        val = 710
    elif row['model'] == 'C5' and row['x'] > 710 and row['score'] <= 745:
        val = 745 
    elif row['CREDIT_MODEL_CODE'] == 'C5' and row['x'] > 745:
        val = 999
    elif row['model'] == 'C5' and row['x'] == 'X': 
        val = 3
    elif row['model'] == 'C5' and row['x'] == 'T': 
        val = 2
    elif row['model'] == "":
        val = 1
    return val

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

I've also tried using NaN and Null in place of "". Anyone know how I can add null values based on other conditions using an if-elif statement?

I keep getting the following error:

 48 
 49     else:

---> 50 val == "" 51 52 return val

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

Aucun commentaire:

Enregistrer un commentaire