Home > Blockchain >  Merging two data frames and keeping the extra rows from first df
Merging two data frames and keeping the extra rows from first df

Time:10-26

I have 2 data frames df1 and df2

df1

        A  B 
id0     a  3      
id1     b  4      
id2     c  0 

df2

       A   B 
id2   aa  80      
id3   d   44      
id4   r   100 

I want to join concat df1 and df2 in such a way that all rows of df1 are retained and if there are rows with the same index in df2( id2 ; in this case ); its dropped from df2.

Final df should look like

        A  B 
id0     a  3      
id1     b  4      
id2     c  0
id3     d   44      
id4     r   100

How can it be done in pandas python?

Regards

CodePudding user response:

You can use combine_first, it is specifically designed for this operation:

df1.combine_first(df2)

output:

     A    B
id0  a    3
id1  b    4
id2  c    0
id3  d   44
id4  r  100

CodePudding user response:

Use concat with filter first duplicates by Index.duplicated:

df = pd.concat([df1, df2])
df = df[~df.index.duplicated()]
print (df)
     A    B
id0  a    3
id1  b    4
id2  c    0
id3  d   44
id4  r  100
  • Related