1

I have two data frames:

   df:
      col1  col2
    0   x   1
    1   a   2
    2   b   3
    3   c   4

and

df2:
      col1  col2
    0   x   1
    1   a   2
    2   f   6
    3   c   4

And I want to obtain data frame in which new row from df2 will be added to new data frame after row with the same index from the df, like this:

  col1  col2
0   x   1
1   a   2
2   b   3
3   f   6
4   c   4
Qwedon
  • 23
  • 5
  • 1
    `df1.merge(df2, how='outer')` or `df2.merge(df1, how='outer')` –  Mar 14 '22 at 15:08
  • I assume https://stackoverflow.com/q/53645882 asnwers your question. If it doesn't, please let me know :) –  Mar 14 '22 at 15:10
  • It adds new row from df2 at the end of new df, but I need to add this value straight after row with index 2 – Qwedon Mar 14 '22 at 15:13
  • Ok, I see you're question isn't a dupe. I reopened it :) –  Mar 14 '22 at 15:15

1 Answers1

1
df1 = pd.DataFrame({
    'col1': ['x', 'a', 'b', 'c'],
    'col2': [1, 2, 3, 4]
})

df2 = pd.DataFrame({
    'col1': ['x', 'a', 'f', 'c'],
    'col2': [1, 2, 6, 4]
})

In order to get your output, I concatenated the two dataframes and sorted by the index, as requested, then you can set the index in order with reset_index().

df = pd.concat([df1, df2]).drop_duplicates().sort_index().reset_index(drop=True)
# Output
  col1  col2
0    x     1
1    a     2
2    b     3
3    f     6
4    c     4
Titouan L
  • 1,182
  • 1
  • 8
  • 24