Pankaj Singh Pankaj Singh - 1 year ago 117
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)

Answer Source

You can useapply method:

dfUnderInterpretation['Status_Desc'] = dfUnderInterpretation['Status'].apply(lambda x: statusInterpretation.get(x))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download