Q:

Add columns to Pandas dataframe based on another dataframe and set values to zero

I have two Pandas dataframes, as shown below:
import pandas as pd
main_df = pd.DataFrame({
    'day1': [1, 2, 3, 4],
    'day2': [2, 1, 3, 4],
    'day3': [3, 1, 2, 5],
    'day4': [2, 1, 3, 5],
    'day5': [4, 1, 2, 3],
    'day6': [5, 3, 4, 2]}, index=['a', 'b', 'c', 'd'])

df = pd.DataFrame({
    'day1': [0, 1, 0],
    'day3': [0, 0, 1]
})

I want to add the columns in main_df to df and set their values to 0. My expected output is:
df
    day1  day2  day3  day4  day5 day6
0    0      0    0      0    0     0
1    1      0    0      0    0     0
2    0      0    1      0    0     0

I can do this the following way in a loop:
cols_to_add = main_df.columns[~main_df.columns.isin(df.columns)]
for c in cols_to_add:
    df[c] = 0

Is there a way I do it without looping? Note that the indices of both dataframes are different.

A:

You can try using dict and assign:
cols_to_add = main_df.columns[~main_df.columns.isin(df.columns)]
d = dict.fromkeys(cols_to_add, 0)
df.assign(**d)

Or
pd.concat([df, pd.DataFrame(columns = cols_to_add)]).fillna(0)

   day1     day3    day2    day4    day5    day6
0   0       0       0       0       0       0
1   1       0       0       0       0       0
2   0       1       0       0       0       0

