Use column of list values and apply as keys to another column of dictionary values on pandas dataframe

Say I have a dataframe called “result” that consists of two columns, one that has list values and the other has dictionary values like this:

[06052, 06710, 06513, 06604]              

{'06710': 'Program1', '06604': 'Program2', '06513': 'Program2', '06106': 'Program3', '06052': 'Program4', '06082': 'Program5'}

I’m trying to use the list column as keys (each element in list) to map to the dictionary column to create a new column that is the output values.

Desired Sample Output:

I can make it work for single cases by doing the following: example for index = 2

[result.Program_Dict_Column[2][i] for i in result.List_Column[2]]

But I can’t seem to make this work for all dataframe values.

I’ve tried:

1.making a function then using lambda to apply:

def get_values(dics, lists):
    for k,v in dics.items():
        return [v[i] for i in lists]

result["Desired_Programs"] = result.apply(lambda x: get_values(x.Program_Dict_Column, x.List_Column),axis=1)

however I get an error: TypeError: string indices must be integers

Any help would be greatly appreciated.


your list consists of numbers and cannot be directly used as keys of your dict, which are strings – though a converison is simple and I will not get to that part

df=pd.DataFrame({'List_Column':[['06052', '06710', '06513', '06604']], 'Program_Dict_Column':[{'06710': 'Program1', '06604': 'Program2', '06513': 'Program2', '06106': 'Program3', '06052': 'Program4', '06082': 'Program5'}

def getValue(row):
    return [row['Program_Dict_Column'][x] for x in row['List_Column']]

Leave a Reply

Your email address will not be published. Required fields are marked *