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!
>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