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

Viewed 36

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.

2 Answers

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

Another way is using df.reindex with df.set_index

df['D'] = df.set_index('B').reindex(df['A'])['C'].values
df

    A   B   C   D
0  n1  n2  n4  n6
1  n2  n3  n5  n4
2  n3  n1  n6  n5
Related