0

I have two dataframes:

Df_1:

  A  B  C  D   
1 10 nan 20 30
2 20 30 20 10

Df_2:

  A  B 
1 10 40
2 30 70

I want to merge them and have this final dataframe.

  A  B  C  D
1 10 40 20 30
2 20 30 20 10
3 30 70 nan nan

How do I do that?

  • 1
    Possible duplicate of [Pandas Merging 101](https://stackoverflow.com/questions/53645882/pandas-merging-101) – Nicolas Gervais Nov 23 '19 at 20:06
  • Could you please describe in details how you want to merge rows? For example what result will be if df_2 = [[10 40] [10 30]]? and if df_2 = [[nan 40] [30 70] [nan 30]] ? What are the rules of merging rows? – Stepan Nov 23 '19 at 21:45

1 Answers1

0

Looking at the expected result, I think, the index in the second row of Df_2 should be 3 (instead of 2).

Run Df_1.combine_first(Df_2).

The result is:

      A     B     C     D
1  10.0  40.0  20.0  30.0
2  20.0  30.0  20.0  10.0
3  30.0  70.0   NaN   NaN

i.e. due to possible NaN values, the type of columns is coerced to float.

But if you want, you can revert this where possible, by applying to_numeric:

Df_1.combine_first(Df_2).apply(pd.to_numeric, downcast='integer')
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41