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?

2
  • why you have a df['A']==1? you didn't had anything indicating if B=99 be updated when A is 1?
    – Naveed
    Oct 7, 2022 at 19:31
  • just edited question to reflect that, realized I forgot to mention that aspect.
    – Luke Haws
    Oct 7, 2022 at 19:39

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
2
  • 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
    – Luke Haws
    Oct 7, 2022 at 19:40
  • 1
    thank you Naveed! mask solution worked for the edit as well
    – Luke Haws
    Oct 7, 2022 at 19:45

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.