14

I have two pandas dataframes: df1 and df2.

df1 has columns X and Y and weeknum. df2 has columns Z, weeknum, and datetime.

I want to basically keep df1 and have an extra column in it that is corresponding datetime for weeknum.

I can use merge but there must be a cleaner way, without having to drop column Z.

wolfsatthedoor
  • 7,163
  • 18
  • 46
  • 90

1 Answers1

19

You can grab the columns you want in the merge syntax

df1 = df1.merge(df2[['weeknum', 'datetime']], on=['weeknum'])

This will make sure you don't have any unwanted columns of df2 in your result, but you don't have to delete those columns from your second DataFrame in the process.

Mike
  • 6,813
  • 4
  • 29
  • 50
  • 1
    keep in mind that merge defaults to "inner" which is `intersection of keys from both frames, similar to a SQL inner join; ` so you may lose rows from df1 if they don't exist in df2 – Sonic Soul Mar 12 '20 at 23:03