Skip to content
Advertisement

Pandas return separate column value in current index if two separate columns match

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:

  1. Loop through Column A to find a matching value in Column B
  2. If there is a match in Column B I want to grab the value in Column C for the current index and create a Column D with that value.
  3. 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
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement