Find and copy values between 2 dataframes

Question:

I’m having trouble copying some data between 2 dataframes. I have the main_df:

id             date  stuff 
123             NaN      3
456      2022-10-10      6
789      2022-09-15      2
357             NaN      9
159      2022-09-15      3

and second_df:

id   stuff 
321      3
456      6
789      2
351      4

I want to search if an id in second_df is in main_df and copy the date that appear in main_df to second_df. This would be the result:

id   stuff         date
321      3          NaN
456      6   2022-10-10
789      2   2022-09-15
351      4          NaN  

I know that with second_df["id"].isin(main_id["id"]) I can get a dataframe/column/Series with boolean results indicating if the id exists, but I don’t know how to copy the date value.

Hope someone can help me, thanks.

Asked By: Alex Turner

||

Answers:

you can use map to bring over the date value

df2['date']=df2['id'].map(df.set_index('id')['date'])
df2
id  stuff   date
0   321     3   NaN
1   456     6   2022-10-10
2   789     2   2022-09-15
3   351     4   NaN
Answered By: Naveed
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.