How to replace pandas data column with data. Base of values ​​to the value of another column B

I have a dataframe like df = pd.DataFrame ([[1,2, np.nan], [4,5, np.nan], [7,8,9]]) so this would be

        sku  r1   r2
    0    1   2  NaN
    1    4   5  NaN
    2    7   8  9.0

      

if I would like to change the base of values ​​of column r1 to r2, I mean if r2 is not Nan then use r2 to replace r1'value, otherwise keep r1 unchanged

So the result will be:

        sku  r1   r2
    0    1   2  NaN
    1    4   5  NaN
    2    7   9.0  9.0

      

so you see, change from 8 to 9.0 in the third case in this example. I am a new pandas learner, I need time to find a solution for this.

Thanks for the help.

+3


source to share


2 answers


You can use mask

with notnull

:

df['r1'] = df['r1'].mask(df['r2'].notnull(), df['r2'])
print (df)

   sku   r1   r2
0    1  2.0  NaN
1    4  5.0  NaN
2    7  9.0  9.0

      



Or loc

:

df.loc[df['r2'].notnull(), 'r1'] = df['r2']
print (df)
   sku   r1   r2
0    1  2.0  NaN
1    4  5.0  NaN
2    7  9.0  9.0

      

+3


source


Use np.where

:

df['r1'] = np.where(df['r2'].notnull(),df['r2'],df['r1'])
df

      



Output:

   sku   r1   r2
0    1  2.0  NaN
1    4  5.0  NaN
2    7  9.0  9.0

      

+1


source







All Articles