mercredi 10 juin 2020

multiple IF statement on a dataframe using a list out of range

I'm looking for a solution to find a correct way to make this function.

On one hand a df with two columns id and category. On the other hand a list which contains id too.

The purpose is, if df['id'] has got the same id from the list and the category is equal to category written below then replace the category value by a new one.

def replace_category(row):
    """
    Replace category when it's appropriate
    """
    if row['id'] in id_list:
        if row['category'] == 'A1':
            return 'Z1'
        elif row['category'] == 'A2':
            return 'Z2'
        else:
            return row['category']
    else:
        return row['category']

df.apply(replace_category, axis=1)

Could Somebody have a better function to do it ?

Aucun commentaire:

Enregistrer un commentaire