python - 在 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')
任何提示将非常感谢!
解决方案
在这种情况下合并的另一种方法是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
推荐阅读
- javascript - 如何在性能不错的浏览器上使用python和opencv
- python - Python中的Word文档操作
- reactjs - 无法使用 JEST(使用 Typescript)和 React 环境模拟节点模块
- apache-flink - Flink 在检查点失败时不会失败
- javascript - 如何使用 matter.js 获得类似气泡的功能?
- c# - EF core 3.1+Pomelo Scaffold-DbContext 防止视图代码生成
- azure-active-directory - 在 Azure AD 门户上,在哪里可以找到包含在 ID 令牌中以进行身份验证的用户的“子”声明值
- android - 类型 sdk.chat.core.BuildConfig 被定义多次
- python - 如何分割/裁剪重叠的字母图像python
- android - 在 Android 中使用 MutableData.value 不起作用