根据条件合并两个数据框

时间:2018-11-17 11:50:43

标签: python dataframe

我想基于两个数据框之间的fact_date和scen条件匹配来合并两个数据框,然后将altdate列添加到第二个数据框。

第一个数据帧如下所示:

          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
...

第二个数据帧如下所示:

          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
...

输出应如下所示:

          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
...

2 个答案:

答案 0 :(得分:1)

我不完全理解您的意思,但我认为您只想加入。如果您使用的是熊猫,应该是这样的:

df2 = df2.join(df1,on=['fact_date','scen'],how='left')

希望这会有所帮助。

答案 1 :(得分:1)

我会尝试

Map<String, InstanceClass>map;

返回

df2.merge(df1, on=['fact_date', 'scen'])