I have a sort of ‘master’ dataframe that I’d like to append only matching columns from another dataframe to
JavaScript
x
8
1
df:
2
A B C
3
1 2 3
4
5
df_to_append:
6
A B C D E
7
6 7 8 9 0
8
The problem is that when I use df.append()
, It also appends the unmatched columns to df.
JavaScript
1
6
1
df = df.append(df_to_append, ignore_index=True)
2
Out:
3
A B C D E
4
1 2 3 NaN NaN
5
6 7 8 9 0
6
But my desired output is to drop columns D and E since they are not a part of the original dataframe? Perhaps I need to use pd.concat
? I don’t think I can use pd.merge
since I don’t have anything unique to merge on.
Advertisement
Answer
Using concat
join='inner
JavaScript
1
6
1
pd.concat([df,df_to_append],join='inner')
2
Out[162]:
3
A B C
4
0 1 2 3
5
0 6 7 8
6