Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace value in column in pandas dataframe based on another column value in same row?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading