通过具有重复值的列连接数据框

问题描述 投票:0回答:1

有两个表df1和df2。 df1 列是 id、预测日期,df2 列是 id 和实际日期。

df1 = pd.DataFrame({
                    'id': ['1', '1', '1', '2', '2', '2', '3', '3'],
                    'predicted_date': ['2022-01-01', '2022-02-01', '2022-03-01', '2022-01-01', '2022-02-01', '2022-03-01', '2022-01-01','2022-02-01']
                   })

df2 = pd.DataFrame({
                    'id': ['1', '1', '2', '2', '3', '3', '3', '3'],
                    'actual_date': ['2022-01-02', '2022-02-02', '2022-03-02', '2022-01-02', '2022-02-02', '2022-03-02', '2022-01-02','2022-02-02']
                   })

我想加入他们以获得一个包含 id、preicted_date 和actual_date 的数据框。 Predicted_date 和actual_date 应与ids 相对应。

我尝试连接,但 id 重复,因此结果不正确。如果要合并数据帧,则会重复预测日期或实际日期观察结果。

df_new = pd.concat([df1, df2], axis = 1)

使用concat,结果是:

enter image description here

我想要一些类似的想法:

I want to have this. There can be NAs instead of blank.

如何才能做到?

python pandas join merge concatenation
1个回答
0
投票

尝试使用使用 groupby id 创建的帮助列、键:

df1.assign(key=df1.groupby('id').cumcount())\
   .merge(df2.assign(key=df2.groupby('id').cumcount()), 
          on=['id', 'key'], 
          how='outer')\
   .drop('key', axis=1)

输出:

  id predicted_date  key actual_date
0  1     2022-01-01    0  2022-01-02
1  1     2022-02-01    1  2022-02-02
2  1     2022-03-01    2         NaN
3  2     2022-01-01    0  2022-03-02
4  2     2022-02-01    1  2022-01-02
5  2     2022-03-01    2         NaN
6  3     2022-01-01    0  2022-02-02
7  3     2022-02-01    1  2022-03-02
8  3            NaN    2  2022-01-02
9  3            NaN    3  2022-02-02
© www.soinside.com 2019 - 2024. All rights reserved.