1

I want to copy data for 3 columns (Date, Info, Title) from df2 to df1 if those columns from df1 is empty.

I have been able to do this using the code below and it works.

df1['Date'] = np.where(df1['Date'].isnull(),df2['Date'],df1['Date'])
df1['Info'] = np.where(df1['Info'].isnull(),df2['Info'],df1['Info'])
df1['Title'] = np.where(df1['Title'].isnull(),df2['Title'],df1['Title'])

What I have discovered recently is that df1 and df2 always has the same number of rows, but not always in the same order, so the data being copied has been incorrect.

Both df1 and df2 will always have the same number of rows and matching 'ID' (unique). I believe I am able to sort both df1 and df2 by 'ID' which should solve my problem, but I think that may be less robust than matching the IDs.

Logically in my head it's easy, I simply add a condition to lookup the matching df1['ID'] with df2['ID'], but I don't know how to do this. I am new with pandas and haven't programmed in over 10 years.

If someone can please let me know how I can do this please.

UPDATE:
Thanks everyone for answer, but I was really struggling with the left, right, inner, outer etc.
I did do some research and managed to find something which seems to have worked quite well for what I needed. I used this code below, 3 times, for Date Info and Title.

df1['Date'] = df1['Date'].fillna(df1['ID'].map(df2.set_index('ID')['Date']))

Thanks for all your help

AudioGuy88
  • 11
  • 4

0 Answers0