首页 > 解决方案 > 在 Id 和 year 上合并两个数据框 pandas,其中 year 缺少值

问题描述

我有两个数据框(dfA 和 dfB),下面给出了一个示例。我想加入数据框以产生给定的结果

dfA
Id, year, B, D
1,  2010, 15, 33
1,  2011, 24, 72
1,  2012, 30, 16

dfB
Id, year, A, C
1,  2009, 100, 1
1,  2010, 75, 7
1,  2012, 60, 3
1, 2013, 42, 4

Result
Id, year, A, B, C, D
1, 2009,100, 0, 1, 0
1, 2010,75,15, 7, 33
1, 2011,0, 24, 0, 72
1, 2012,60, 30, 3, 16
1, 2013,42, 0, 4, 0

试图

我已经尝试使用 pandas.merge 尝试内、外、左和右连接,但无法获得所需的结果!

result = pd.merge(dfA,dfB,on=['Id','year'], how = 'outer')

任何提示将非常感谢!

标签: pythonpandasdataframe

解决方案


在这种情况下合并的另一种方法是pandas concat,在列轴上连接:

(pd.concat([df1.set_index(['Id','year']),
            df.set_index(['Id','year'])],axis=1)
 .reset_index()
 .fillna(0)
.reindex(columns=['Id','year','A','B','C','D'])
)

    Id  year    A       B   C   D
0   1,  2009,   100,    0   1.0 0.0
1   1,  2010,   75,     15, 7.0 33.0
2   1,  2011,   0       24, 0.0 72.0
3   1,  2012,   60,     30, 3.0 16.0
4   1,  2013,   42,     0   4.0 0.0

推荐阅读