python - 合并两个表
问题描述
我有两张桌子。我需要用cx1
,cx2
和Date
键合并两个表。如何?
fist table
cx1 Date Amount
1 11/1/2019 400
1 12/1/2019 200
2 15/1/2019 400
3 16/1/2019 500
Second Table
cx2 Date Amount
1 11/1/2019 300
2 16/1/2019 200
3 16/1/2019 400
Final output
cx Date Amount_1 Amount_2
1 11/1/2019 400 300
1 12/1/2019 0 300
2 15/1/2019 400 0
2 16/1/2019 0 200
3 16/1/2019 500 400
解决方案
使用 , , pd.merge
,Series.fillna
的Series.sort_values
组合Series.rename
:
df = pd.merge(
df1.rename(columns={'cx1': 'cx'}), df2.rename(columns={'cx2': 'cx'}),
on=['cx', 'Date'], how='outer', suffixes=('_1', '_2'))
df = df.sort_values(by='cx').fillna(0)
df[['cx', 'Amount_1', 'Amount_2']] = df[['cx', 'Amount_1', 'Amount_2']].astype(int)
结果:
cx Date Amount_1 Amount_2
0 1 11/1/2019 400 300
1 1 12/1/2019 200 0
2 2 15/1/2019 400 0
4 2 16/1/2019 0 200
3 3 16/1/2019 500 400
推荐阅读
- sql - sql中的组合列表
- heroku - heroku[web.1]:进程以状态 143 退出
- reactjs - 当我单击以增加购物车中商品的数量时,它增加了两个而不是一个
- c++ - 如何编写模板/概念来检查类型是否满足命名要求 DefaultInsertable
- java - 如何编写 Dockerfile 将我的 war 文件部署到 jboss 7.2 中?
- python - 如何在pyqt5的QTextEditor中加粗选定的文本
- pug - 在本地提供数据时,Bootstrap-Table 不搜索和总计行
- python - 如何将具有整数和小数的数字文件附加到python中的列表/数组
- c++ - 添加 3*3 矩阵的代码有什么错误?
- android - 错误:没有为类“对象”定义方法“数据”?