3

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 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.