首页 > 解决方案 > 合并两个表

问题描述

我有两张桌子。我需要用cx1,cx2Date键合并两个表。如何?

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

标签: pythonpandasdataframe

解决方案


使用 , , pd.merge,Series.fillnaSeries.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

推荐阅读