0

I have a dataframe with two columns. Column A contains values 0 and 1 and column B contains values 0 and 99. Like so:

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

   A   B
0  0  99
1  0   1
2  0   0
3  1  99
4  1  99
5  0   1
6  0   1
7  1  99
8  1  99
9  0  99

I need to replace all values of 99 with 0s within column B when the corresponding value of column A is 1, and I tried this:

    df = df[df['A']==1].replace({'B': {99: 0}})

   A  B
3  1  0
4  1  0
7  1  0
8  1  0

but when trying this, I lose the portion of the dataframe where A is 0. How can I perform this without losing that portion?

3
  • why you have a df['A']==1? you didn't had anything indicating if B=99 be updated when A is 1? Commented Oct 7, 2022 at 19:31
  • just edited question to reflect that, realized I forgot to mention that aspect. Commented Oct 7, 2022 at 19:39
  • This question is similar to: Change values in one column on the basis of the values in another column. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented May 5 at 17:04

1 Answer 1

2

here is one way to do it

using Loc
df.loc[(df['A']== 1) & (df['B']==99), 'B'] = 0
df

OR

# using mask
df['B']= df['B'].mask((df['A']== 1) & (df['B']==99), 0)
df
    A   B
0   0   0
1   0   1
2   0   0
3   1   0
4   1   0
5   0   1
6   0   1
7   1   0
8   1   0
9   0   0
Sign up to request clarification or add additional context in comments.

2 Comments

realized my initial question did not mention I need to only change B's value when A's corresponding value is 1, not 0. I apologize
thank you Naveed! mask solution worked for the edit as well

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.