gpt4 book ai didi

python - 根据条件合并两个 DataFrame

转载 作者:行者123 更新时间:2023-12-01 01:25:51 31 4
gpt4 key购买 nike

我想根据两个数据帧之间的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
...

最佳答案

我会尝试

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

返回

    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

关于python - 根据条件合并两个 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53350947/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com