Pankaj Singh Pankaj Singh - 4 months ago 43
Python Question

pandas - using a column as a key for a dictionary

One of the columns "Status" in my dataframe dfUnderInterpretation has values like "OK", "Missing" and "New".

Another variable statusInterpretation is a dict:
{'OK': 'INFO', 'New': 'WARN', 'Missing': 'ERROR' }

I want to create a new column 'Interpretation' with dict values based on index in "Status" column of my dataframe.

This below of course wont work because dfUnderInterpretation['Status'] is a list.

dfUnderInterpretation['Interpretation'] = statusInterpretation.get(dfUnderInterpretation['Status'], None)


You can useapply method:

dfUnderInterpretation['Status_Desc'] = dfUnderInterpretation['Status'].apply(lambda x: statusInterpretation.get(x))