首页 > 解决方案 > 合并 2 个不同的数据框 - Python 3.6

问题描述

想要合并 2 个表格和空白应填充第一个表格行。

DF1:

Col1 Col2 Col3
A    B    C

DF2:

Col6  Col8
1      2
3      4
5      6
7      8
9      10

我期待结果如下:

Col1 Col2 Col3 Col6  Col8
A    B    C    1     2
A    B    C    3     4
A    B    C    5     6
A    B    C    7     8
A    B    C    9     10

标签: python-3.xpandasdataframemerge

解决方案


使用assign,但随后有必要更改列的顺序:

df = df2.assign(**df1.iloc[0])[df1.columns.append(df2.columns)]
print (df)
  Col1 Col2 Col3  Col6  Col8
0    A    B    C     1     2
1    A    B    C     3     4
2    A    B    C     5     6
3    A    B    C     7     8
4    A    B    C     9    10

或者并通过向前填充concat替换s :NaNffill

df = pd.concat([df1, df2], axis=1).ffill()
print (df)
  Col1 Col2 Col3  Col6  Col8
0    A    B    C     1     2
1    A    B    C     3     4
2    A    B    C     5     6
3    A    B    C     7     8
4    A    B    C     9    10

推荐阅读