why doesn't pandas column get overwritten by other column?

Question:

I am trying to overwrite the row values for column A and B in df1 with the values from df2. My dfs look as such:

df1
    'A'  'B'   'C'
23   0   cat   orange
24   0   cat   orange
25   0   cat   orange

df2
    'A'  'B'   'C'
56   2   dog   yellow
64   4   rat   orange
85   2   bat   red

The indices here are different and I would like to overwrite row 25 of df1 with the values of 64 from df2 for only column A and B.

I have tried something like this

df1[['A','B']].loc[25] = df2[['A','B']].loc[64]

This executes but doesn’t actually seem to overwrite anything as when I call df1[['A','B']].loc[25] I still get the original values. I would expect the new df1 to look like this:

df
    'A'  'B'   'C'
23   0   cat   orange
24   0   cat   orange
25   2   bat   orange

Can someone explain why this doesn’t work for me please?

Asked By: geds133

||

Answers:

Cause df1[[‘A’,’B’]] is a new DataFrame, try:

df1.loc[25, ['A','B']] = df2[['A','B']].loc[64]
Answered By: Liu Leo
df1.loc[25, ['A', 'B']] = df2.loc[64, ['A', 'B']]
Answered By: JayPeerachai
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.