filter pandas dataframe by inserting zeros based on another data farme index

is there anyway to filter the first dataframe based on the index of second dataframe and generate the output dataframe? In first datafarme, we filterout the rows whose index are present in second dataframe and need to insert whole 0 zero in place of index value of second dataframe.

first dataframe

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

second dataframe

   C1  C2  C3  C4
A   1   1   1   1

output dataframe

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

>Solution :

If you always have 1s in df2, a simple method would be a subtraction:

out = df1.sub(df2, fill_value=0)

Otherwise, build a mask using reindexed df2:

out = df1.mask(df2.notna().reindex(index=df1.index, columns=df1.columns, fill_value=False), 0)

Output:

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

Leave a Reply