Merge 2 Different Data Frames - Python 3.6

試著忘記壹切 提交于 2021-02-05 07:51:51

问题


Want to merge 2 table and blank should fill with first table rows.

DF1:

Col1 Col2 Col3
A    B    C

DF2:

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

I am expecting result as below:

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

回答1:


Use assign, but then is necessary change order of columns:

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

Or concat and replace NaNs by forward filling with ffill:

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



回答2:


you can merge both dataframes by index with outer join and forward fill the data

df1.merge(df,left_index=True,right_index=True,how='outer').fillna(method='ffill')

Out:

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


来源:https://stackoverflow.com/questions/52385502/merge-2-different-data-frames-python-3-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!