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

pandas compare two dataframes and creating 0 columns

I have two dataframes as follows:

df1

Year    Column1   Column2   Column3
2022    1          2         3
2022    5          7         9


df2

Year    Column1    Column4    Column5
2022     1          2          4

What I want to achieve is that in df2, I want to detect the missing columns (in this case it would be Column2 and Column3 and fill 0)
So my df2 would ultimately look like:

df2

Year     Column1   Column4   Column5   Column2   Column3
2022      1         2         4         0         0

How do I achieve this? I tried map but wasnt able to get it to work.
Thanks!

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

>Solution :

You can loop over the columns in df1, check if they are in df2 and, if they are not, add them in like this:

for col in df1.columns:
    if col not in df2.columns:
        df2[col] = 0
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