Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading