Search code examples
pythonpandasdictionarydefaultdictmap-function

Usage of .map with defaultdict


I have a pandas dataframe and I have to fill a new column based on the values of an existing column, associating the values of a dictionary.

mydict={'key1':'val1', 'key2':'val2'}
df['new_col']=df['keys'].map(mydict)

Now I have a similar problem, but the dictionary is now a defaultdict(list)

my_defdict=defaultdict(list)
my_defdict={'key1':['val1','item1'], 'key2':['val2','item2']}

and I need a new column with the second element of the list, something like

df['new_col2']=df['keys'].map(my_defdict()[1])

which is of course wrong. How can I perform this operation without creating another normal dictionary?


Solution

  • Assuming all your values have at least two items per list, add an str[1] at the end:

    df['new_col2'] = df['keys'].map(my_defdict).str[1]
    

    Or,

    df['new_col2'] = df['keys'].map(my_defdict).str.get(1)