Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simultaneously replace multiple values in a pandas df

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
like image 738
jonboy Avatar asked Oct 14 '25 04:10

jonboy


1 Answers

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
like image 143
BENY Avatar answered Oct 16 '25 18:10

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!