Map multiple columns from pandas DataFrame into one column

Viewed 1324

I have a pandas DataFrame as follows:

   a  b
0  1  3
1  2  4

I have a dictionary whose keys are tuples of the pandas DataFrame columns e.g.

{(1, 3) : 5, (2, 4) : 6}

I want to a create a new column in the pandas DataFrame e.g. df['c'] based on this mapping. What is the best way to do this?

So the final DataFrame should be:

   a  b  c
0  1  3  5
1  2  4  6
3 Answers

Given your DataFrame, and your dict, you could list and zip which converts to tuple, then map your d:

df['c'] = pd.Series(list(zip(df.a,df.b))).map(d)

   a  b  c
0  1  3  5
1  2  4  6

You can use pandas.DataFrame.agg along axis=1 to aggregate into tuple, then pandas.Series.map the mappings and assign it to column c:

>>> d = {(1, 3) : 5, (2, 4) : 6}
>>> df['c'] = df.agg(tuple, 1).map(d)
>>> df
   a  b  c
0  1  3  5
1  2  4  6

Use DataFrame.join with Series constructor - keys are converted to MultiIndex:

d = {(1, 3) : 5, (2, 4) : 6}

df1 = df.join(pd.Series(d,name='c'), on=['a','b'])
print (df1)
   a  b  c
0  1  3  5
1  2  4  6

Detail:

print (pd.Series(d,name='c'))
1  3    5
2  4    6
Name: c, dtype: int64
Related