4

I am trying to replace values in a pandas df at the same time. It appears the function does this successively, so the values I replace end up being written over. Using below, where X == Left, I want to replace A-D, B-C, C-B, D-A. It works well if I only perform one of these calls but when I do all four it doesn't. Below are my attempts:

import pandas as pd

df = pd.DataFrame({   
    'X' : ['Left','Left','Left','Left','Right','Right','Right','Right'],
    'Y' : ['A','B','C','D','A','B','C','D'],            
    })

ATTEMPT1:

df[(df['X'] == 'Left') & (df['Y'] == 'A')] = df['Y'].map({'A': 'D'})
df[(df['X'] == 'Left') & (df['Y'] == 'B')] = df['Y'].map({'B': 'C'})
df[(df['X'] == 'Left') & (df['Y'] == 'C')] = df['Y'].map({'C': 'B'})
df[(df['X'] == 'Left') & (df['Y'] == 'D')] = df['Y'].map({'D': 'A'})

Out:

       X  Y
0      D  D
1      C  C
2      B  B
3      A  A
4  Right  A
5  Right  B
6  Right  C
7  Right  D

ATTEMPT 2:

df.loc[(df['X'] == 'Left') & (df['Y'] == 'A'), 'Y'] = 'D'
df.loc[(df['X'] == 'Left') & (df['Y'] == 'B'), 'Y'] = 'C'
df.loc[(df['X'] == 'Left') & (df['Y'] == 'C'), 'Y'] = 'B'
df.loc[(df['X'] == 'Left') & (df['Y'] == 'D'), 'Y'] = 'A'

Out:

       X  Y
0   Left  A
1   Left  B
2   Left  B
3   Left  A
4  Right  A
5  Right  B
6  Right  C
7  Right  D

Intended Output:

       X  Y
0   Left  D
1   Left  C
2   Left  B
3   Left  A
4  Right  A
5  Right  B
6  Right  C
7  Right  D
1
  • 1
    great example of a well written question +1 Commented Apr 23, 2020 at 2:21

1 Answer 1

5

Do replace once:

df.Y.update(df.loc[df['X'] == 'Left','Y'].replace({'A': 'D','B': 'C','C': 'B','D': 'A'}))
df
       X  Y
0   Left  D
1   Left  C
2   Left  B
3   Left  A
4  Right  A
5  Right  B
6  Right  C
7  Right  D
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.