Pandas / How to drop a line/error during the map process?

Viewed 19

Hello

Here is my dataframe :

data = pds.DataFrame({'food': ['bacon','porc braisé','bacon','Pastrami','corned beef','BAcon','pastrami','jambon','saumon fumé'],gr' : [4,3,6,7.5,8,3,5,6,7]})

Here is my dict

nourr= { 'bacon':'porc','porc braisé':'porc', 'pastrami':'boeuf','corned beef':'boeuf','jambon':'porc','saumon fumé': 'poisson'}

Here is my mapping function for the new column of my dataframe :

data["animal"]=data["food"].map(lambda x: nourr[x.lower()])

But if there is a mismatch between the food column and the nourr dict, it throws an error. Is there a way to ignore this kind of error : e.g if 'bacon' is written like "bacond" :

KeyError: 'bacond'

1 Answers

Solution credited to @Psidom

data["food"].map(lambda x: nourr.get(x.lower()))
Related