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

Time:10-08

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?

CodePudding user response:

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
  • Related