Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dataframe replace rows by other

I have two dataframes in python:

df1:

code | A | B
1      p   r
2      q   s
3      t   u

and

df2:

code | A | B
1      v   w
3      x   y
4      z   I

What I wanted to do was to replace the rows of df1 which exist (based on 'code' column) in df2 by df2's values... (note that I don't want to include rows from df2 that are not in df1 (based on 'code' column)

I don't want to merge or join them! because it seems that they will duplicate the columns!

The output should look like:

code | A | B
1      v   w
2      q   s
3      x   y

I have written some code to achieve this but it seems that it takes a very long time or it doesn't even work... (no errors!)

#result
df = pd.DataFrame(columns=df1.columns)

#replace these
ind1 = df2.ncodpers

#iterate
for i, row in df1.iterrows():
    if (row['code'] in ind1):
        temp = df2[df2['code'] == row['code']]
        df=df.append(temp)
    else:
        df=df.append(row)

df1 = df

is there an easier way to achieve this? Thank you

like image 868
uncommon_name Avatar asked Aug 12 '26 14:08

uncommon_name


1 Answers

You can use reindex_like with combine_first:

print (df2.set_index('code')
          .reindex_like(df1.set_index('code'))
          .combine_first(df1.set_index('code'))
          .reset_index())

   code  A  B
0     1  v  w
1     2  q  s
2     3  x  y
like image 98
jezrael Avatar answered Aug 15 '26 06:08

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!