question.it
question.it

Reputation: 2978

Merge 2 Different Data Frames - Python 3.6

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

Upvotes: 1

Views: 87

Answers (2)

jezrael
jezrael

Reputation: 863361

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

Upvotes: 1

Naga kiran
Naga kiran

Reputation: 4607

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

Upvotes: 1

Related Questions