Search code examples
pandasmatching

Change Column Value if Value Exists In Another Column


Given the following pandas df -

Holding Account Account Type Column A Column B
Rupert 06 (23938996) Holding Account 1825973 1702598
Rupert 07 (23938996) Holding Account 1697870 1825973
- - - -
Caroline 06 (0131465) Holding Account 11112222 5435450
Caroline 07 (0131465) Holding Account 7896545 11112222

I am trying to find a way to do the following -

  • Step 1 - For the entire df, search for instances of Column B values appearing in Column A
    (example: Column B of Caroline 07 == Column A of Caroline 06)
  • Step 2 - Rows that meet the above criteria should have there Column B value changed to the Column B value of the row who they matches
    (example: Caroline 7 Column B value will change from 11112222 to 5435450

This means the pandas df will now look as follows -

Holding Account Account Type Column A Column B
Rupert 06 (23938996) Holding Account 1825973 1702598
Rupert 07 (23938996) Holding Account 1697870 1702598
- - - -
Caroline 06 (0131465) Holding Account 11112222 5435450
Caroline 07 (0131465) Holding Account 7896545 5435450

Does anyone have some suggestions about how I might achieve such a result?

Useful info:

  • Dypes = object

Solution

  • please try this:

    import numpy as np
    df['Column B'] = np.where(df['Column B'].isin(df['Column A'].values),df['Column B'].shift(),df['Column B'])