filter the pandas data frame by replacing the values of another data frame

First data frame:

                  C1  C2  C3  C4
               A   0   0   0   0
               B   0   0   0   0
               C   0   0   0   0
               D   0   0   0   0
               E   1   1   1   1
               F   1   1   1   1

Second data frame:

                   C1  C2  C3  C4
               B   1   1   1   1
               C   1   1   1   1
               D   1   1   1   1

Output data frame:

                   C1  C2  C3  C4
               A   0   0   0   0
               B   1   1   1   1
               C   1   1   1   1
               D   1   1   1   1
               E   0   0   0   0
               F   0   0   0   0

Is there any way to produce this output dataframe? In output dataframe,we filtered first data frame based on values of second data frame, only those values are kept 1 which are 1 in second dataframe all other values are zero.

>Solution :

You can set all the values in df1 to 0, then update with the values from df2:

df1[:] = 0
df1.update(df2)

Output:

   C1  C2  C3  C4
A   0   0   0   0
B   1   1   1   1
C   1   1   1   1
D   1   1   1   1
E   0   0   0   0
F   0   0   0   0

Leave a Reply