I am trying to copy a column of data from one dataframe to another, using the index as a reference. When copying the column, I want to fill any entry that does not appear in both dataframes with a NaN.
For example, I have these two dummy dfs:
df1 =
col_1 col_2 col_3 col_4
index
A 1 4 7 10
B 2 5 8 11
C 3 6 9 12
df2 =
col_5 col_6
index
A 13 15
C 14 16
And I would like to copy col_5 to df1 based on the shared index so df1 looks like:
df1 =
col_1 col_2 col_3 col_4 col_5
index
A 1 4 7 10 15
B 2 5 8 11 NaN
C 3 6 9 12 16
Since they're different lengths I can't simply do df1['col_5'] = df2['col_5'], and I didn't have any success with a df1.merge(df2, how='left'), and then I'd have to drop any unwanted columns anyway.
Any help appreciated. Thanks!
mergeis the right way to go for this sort of thing. When you say you "didn't have any success" with it, what did you try, and what was wrong with your result?df1['col_5'] = df2['col_5']doesn't work?