vendredi 3 avril 2020

'If-Elif-Else' Function Returning Truth Value Ambiguous - Pandas Dataframe [duplicate]

Attempting to run a function to separate age of house into certain categories, and then create a new column in the original dataframe using the result. Here is the code for the IF Statement:

def sort_age(data):
    if (data["housing_median_age"] > 40) : 
        return ('Cat 5')
    elif ((30 <= data["housing_median_age"]) & (data["housing_median_age"] <= 40)) : 
        return ('Cat 4')
    elif ((20 <= data["housing_median_age"]) & (data["housing_median_age"] < 30)) :
        return ('Cat 3')
    elif (10 <= data["housing_median_age"] < 20) : 
        return ('Cat 2')
    elif (0 <= data["housing_median_age"] < 10) : 
        return ('Cat 1')
    else:
        return ('None')


# Here's the code for the new column:
p1data['age_category'] = p1data.apply(lambda x: sort_age(p1data), axis = 1)


The error message looks like this:

ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index 0')

Aucun commentaire:

Enregistrer un commentaire