Home > Back-end >  How to merge two Dataframes replacing NaN values?
How to merge two Dataframes replacing NaN values?

Time:09-18

I'm working with two tables with the same columns. I need to merge them but replacing null values (identified ad 'N/A').

The first table is my reference. So in cases to different values (and is not 'N/A'), the result of the first table must prevail.

The expected result is one row with 'DistanciaPercorrida' equal to '3km' and 'TempoCorrida' equal to '4min 38s'.

SOLVE:

I used df.replace('?', np.NaN) to transform 'N/A' to NaN value and after df1.set_index('Data').combine_first(df2.set_index('Data')).reset_index()

CodePudding user response:

Use combine_first to fill NaN values from your first dataframe with the values of the second:

>>> df1.set_index('Data').combine_first(df2.set_index('Data')).reset_index()

        Data DistanciaPercorrida TempoCorrida
0  15 de ago                 3km     4min 38s
  • Related