acmyers
acmyers

Reputation: 91

New pandas dataframe column using values from python dictionary

I have a pandas dataframe, for example:

colA      colB 
code1      num
code2      num
code3      num
code4      num
code5      num

I also have a python dictionary, for example:

py_dict = {'code1': [val1, val2, val3, val4, val5], 'code2': [val1, val2, val3, val4, val5], 'code3': [val1, val2, val3, val4, val5], 'code4': [val1, val2, val3, val4, val5], 'code5': [val1, val2, val3, val4, val5]}

What I would like to do is create a new column in the pandas dataframe, call it colC, which uses the key from colA to match the corresponding key/list in py_dict and return the third list value, val3. I've experimented with dataframe.from_dict() and dataframe.update() but not sure how to index the dictionary properly.

Upvotes: 2

Views: 1266

Answers (1)

BrenBarn
BrenBarn

Reputation: 251355

First create a new dict containing only the value you want from each list:

new_dict = {k: v[2] for k, v in py_dict.iteritems()}

Then you can use Series.map

df['new_col'] = df.colA.map(new_dict)

Upvotes: 1

Related Questions