Reputation: 107
I want to merge two DataFrames based on matching the conditions of fact_date and scen between the two dataframes and then add the altdate column to the second dataframe.
The first dataframe looks like the following:
fact_date scen altdate
0 2008-08-18 -1 2008-08-25
1 2008-08-18 0 2008-08-18
2 2008-08-18 1 2008-08-15
3 2008-08-18 2 2008-08-14
4 2008-08-18 3 2008-08-13
5 2008-08-18 4 2008-08-12
6 2008-08-18 5 2008-08-11
7 2008-08-18 6 2008-08-08
8 2008-08-18 7 2008-08-07
9 2008-08-18 8 2008-08-06
...
The second dataframe looks like the following:
fact_date flag scen values
0 2008-08-18 0 -1 462456.29
1 2008-08-18 0 0 1119881.78
2 2008-08-18 0 1 1922320.74
3 2008-08-18 0 2 3559026.11
4 2008-08-18 0 3 3510447.61
5 2008-08-18 0 4 4873269.42
6 2008-08-18 0 5 5098557.55
7 2008-08-18 0 6 4610888.45
8 2008-08-18 0 7 4090821.69
9 2008-08-18 0 8 4219340.84
...
The output should look like the follwoing:
fact_date flag scen values altdate
0 2008-08-18 0 -1 462456.29 2008-08-25
1 2008-08-18 0 0 1119881.78 2008-08-18
2 2008-08-18 0 1 1922320.74 2008-08-15
3 2008-08-18 0 2 3559026.11 2008-08-14
4 2008-08-18 0 3 3510447.61 2008-08-13
5 2008-08-18 0 4 4873269.42 2008-08-12
6 2008-08-18 0 5 5098557.55 2008-08-11
7 2008-08-18 0 6 4610888.45 2008-08-08
8 2008-08-18 0 7 4090821.69 2008-08-07
9 2008-08-18 0 8 4219340.84 2008-08-06
...
Upvotes: 1
Views: 104
Reputation: 10850
I'd try
df2.merge(df1, on=['fact_date', 'scen'])
which returns
fact_date flag scen values altdate
0 2008-08-18 0 -1 462456.29 2008-08-25
1 2008-08-18 0 0 1119881.78 2008-08-18
2 2008-08-18 0 1 1922320.74 2008-08-15
3 2008-08-18 0 2 3559026.11 2008-08-14
4 2008-08-18 0 3 3510447.61 2008-08-13
5 2008-08-18 0 4 4873269.42 2008-08-12
6 2008-08-18 0 5 5098557.55 2008-08-11
7 2008-08-18 0 6 4610888.45 2008-08-08
8 2008-08-18 0 7 4090821.69 2008-08-07
9 2008-08-18 0 8 4219340.84 2008-08-06
Upvotes: 1
Reputation: 2221
I don't fully understand what you are saying, but i think you just want a join. If you are using Pandas it should be like this:
df2 = df2.join(df1,on=['fact_date','scen'],how='left')
Hope this helps.
Upvotes: 1