Say I have the following data frame:
A B C 0 n1 n2 n4 1 n2 n3 n5 2 n3 n1 n6
I have been trying to:
- Loop through
Column A
to find a matching value inColumn B
- If there is a match in
Column B
I want to grab the value inColumn C
for the current index and create aColumn D
with that value. - Given the example data frame above, below would be the solution I’m trying to achieve.
A B C D 0 n1 n2 n4 n6 1 n2 n3 n5 n4 2 n3 n1 n6 n5
I’ve seen lots of answers for excel utilizing match and index, but I literally can’t find anything to help me solve this problem. Any help would be appreciated.
Advertisement
Answer
Use map
with set_index
:
df['D'] = df['A'].map(df.set_index('B')['C'])
Output:
A B C D 0 n1 n2 n4 n6 1 n2 n3 n5 n4 2 n3 n1 n6 n5