WillacyMe WillacyMe - 1 month ago 9
Python Question

How do I map a dictionary with list values to a dataframe?

I need to map a dict to a column in a dataframe but don't know how to do it when the values in the dict are in a list. Ideally I was a new column for the values in pos

[0]
, and another column for the values in pos
[1]
.

dict = {'foo':['A','B'],
'bar':['C','D']}

df = pd.DataFrame([[0,'foo'],
[1,'bar']], columns=['Col1','Col2'])


Below is the usual way I'd go about this task if there was only one dict value.

df['Col3'] = df.Col2.map(dict)

Answer

Series.map() will also accept functions, so you can pass in a lambda function that wraps the lookup dictionary and grabs the list item you want.

dict = {'foo':['A','B'],
        'bar':['C','D']}

df = pd.DataFrame([[0,'foo'],
                   [1,'bar']], columns=['Col1','Col2'])

df['Col3'] = df.Col2.map(lambda x: dict[x][0])
df['Col4'] = df.Col2.map(lambda x: dict[x][1])