Dreamer Dreamer - 16 days ago 5
Python Question

Append based on condition using pandas

I have a data frame

df1
with columns
ID2, Name2, ID3, Name3
. I have other two data frame
df2
(columns:
Name2, ID2
) and
df3
(columns:
Name3, ID3
) with the same columns. I am trying to merge
df2
and
df3
based on matching ID, which I do as follows:

Solution = pd.merge(df2,df3, left_on='ID2',right_on='ID3').sort_values('Name2')


Now I want to append this result to
df1
, only if ID2/ID3 doesn't already exist in
df1
. How do I do that?

Answer

Use isin:

df1.append(Solution[~Solution['ID2'].isin(df1['ID1'])])