Home > Software design >  Pandas Comparision of dataframe wherever zero in the one dataframe make zero on other
Pandas Comparision of dataframe wherever zero in the one dataframe make zero on other

Time:10-08

I wanted to put zero on on dataframe compare to other is there any way to do it please suggest me

Only zero I wanted replace from df1 to df2

df1

  name data1 data2 data3 data4            
  cm1   10     0    30     0              
  cm2    0    20     0    20         
  cm3    1     0    20    NaN        

df2

 name  data1 data2 data3 data4  
 cm1     6    10    15    20
 cm2     9   NaN    20     3
 cm3     1   NaN    20    30

output df2

name  data1 data2 data3 data4  
 cm1     6    0     15    0
 cm2     0   NaN     0    3
 cm3     1    0     20   30

CodePudding user response:

You can check when your df1 is 0, and fillna using your df2:

df1[df1==0].fillna(df2)

prints:

  name  data1  data2  data3  data4
0  cm1    6.0    0.0   15.0    0.0
1  cm2    0.0    NaN    0.0    3.0
2  cm3    1.0    0.0   20.0   30.0

Note that this alignes on indices, so you might want to first set your index in both df to be 'name':

df1.set_index('name',inplace=True)
df2.set_index('name',inplace=True)

new_df2 = df1[df1==0].fillna(df2)

>>> new_df2
  name  data1  data2  data3  data4
0  cm1    6.0    0.0   15.0    0.0
1  cm2    0.0    NaN    0.0    3.0
2  cm3    1.0    0.0   20.0   30.0   

CodePudding user response:

You could find zeros in df1 using df1==0, index them in df2, and set the values to zero.

df2[df1==0]=0
  • Related