Say I have the following data frame:
JavaScript
x
5
1
A B C
2
0 n1 n2 n4
3
1 n2 n3 n5
4
2 n3 n1 n6
5
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.
JavaScript
1
5
1
A B C D
2
0 n1 n2 n4 n6
3
1 n2 n3 n5 n4
4
2 n3 n1 n6 n5
5
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
:
JavaScript
1
2
1
df['D'] = df['A'].map(df.set_index('B')['C'])
2
Output:
JavaScript
1
5
1
A B C D
2
0 n1 n2 n4 n6
3
1 n2 n3 n5 n4
4
2 n3 n1 n6 n5
5