1

I have a DataFrame like below

df = pd.DataFrame({          
    'A' : [x,x,x,x,x],
    'B' : [1,2,1,1,2]        
    })

I would like to replace x by y where df['B'] == 2 I know there are lots of ways but what is the shortest code to accomplish this? I believe np.where is one way but can it change value (or overwrite variable) based on values in another column?

2 Answers 2

1

Here are some alternatives select by both conditions or using replace with select by one condition:

df = pd.DataFrame({          
    'A' : ['x'] * 5,
    'B' : [1,2,1,1,2]        
    })

df.loc[df.B.eq(2) & df.A.eq('x'), 'A'] = 'y'
print (df)
   A  B
0  x  1
1  y  2
2  x  1
3  x  1
4  y  2

Or:

df.A = df.A.mask(df.B.eq(2) & df.A.eq('x'), 'y')

Or:

df.A = df.A.mask(df.B.eq(2), df.A.replace('x','y'))

Or:

df.loc[df['B'].eq(2), 'A'] = df['A'].replace('x', 'y')
Sign up to request clarification or add additional context in comments.

Comments

0

Try using loc:

>>> df.loc[df['B'] == 2, 'A'] = df.loc[df['B'] == 2, 'A'].replace('x', 'y')
>>> df
   A  B
0  x  1
1  y  2
2  x  1
3  x  1
4  y  2
>>> 

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.