stavrop
stavrop

Reputation: 485

Python Pandas Merge dataframe with repeated values

I have two dataframes, lets say df1 & df2 and merge them on a datetime column, with the note that one dataframe has multiple entries for each datetime entry.
I want the value of the second dataframe to be put in each row of the first dataframe with this date.
For example:

df1 is:

date idx1 val
20171001 1 1.435
20171001 2 2.245
20171001 3 1.456
20171001 4 1.656
20171002 1 3.258
20171002 2 8.264
20171002 3 9.841
20171002 4 3.465

df2 is:

date val2
20171001 4
20171002 6

What i want to end up with is:
df3:

date idx val1 val2
20171001 1 1.435 4
20171001 2 2.245 4
20171001 3 1.456 4
20171001 4 1.656 4
20171002 1 3.258 6
20171002 2 8.264 6
20171002 3 9.841 6 
20171002 4 3.465 6

I believe it's rather easy, but my brain has stopped functioning....
Thanks for any help!

Upvotes: 1

Views: 2918

Answers (1)

Zero
Zero

Reputation: 76917

Use

In [1288]: df1.merge(df2)
Out[1288]:
       date  idx1    val  val2
0  20171001     1  1.435     4
1  20171001     2  2.245     4
2  20171001     3  1.456     4
3  20171001     4  1.656     4
4  20171002     1  3.258     6
5  20171002     2  8.264     6
6  20171002     3  9.841     6
7  20171002     4  3.465     6

Upvotes: 2

Related Questions