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.