0

I have two dataframes df1 and df2. df2 is the subset of df1

df1 = df1=[[0,1,0,0],
      [1,2,0,0],
      [2,0,0,0],
      [2,4,0,0]]

df1 = pd.DataFrame(df1,columns=['A','B','C','D'])
>>> df1
   A  B  C  D
0  0  1  0  0
1  1  2  0  0
2  2  0  0  0
3  2  4  0  0

>>> df2
   C  D
2  1  3
3  2  4

I want to append the value of C and D from df2 to df1 based on index.

My expected output:

   A  B  C  D
0  0  1  0  0
1  1  2  0  0
2  2  0  1  3
3  2  4  2  4

2 Answers 2

2

Use DataFrame.update:

notice: this is inplace, so it overwrites your df1 without having it to assign back

Quoted from the docs:

Modify in place using non-NA values from another DataFrame.

Aligns on indices. There is no return value.

df1.update(df2)
   A  B    C    D
0  0  1 0.00 0.00
1  1  2 0.00 0.00
2  2  0 1.00 3.00
3  2  4 2.00 4.00

To convert back to int, use DataFrame.astype:

df1 = df1.astype(int)

   A  B  C  D
0  0  1  0  0
1  1  2  0  0
2  2  0  1  3
3  2  4  2  4

Another solution, but less elegant, is to use addition and then fillna:

(df1 + df2).fillna(df1).astype(int)

Or

df1.add(df2).fillna(df1).astype(int)
   A  B  C  D
0  0  1  0  0
1  1  2  0  0
2  2  0  1  3
3  2  4  2  4
Sign up to request clarification or add additional context in comments.

Comments

0

Another way is using reindex_like and fillna

df_final = df2.reindex_like(df1).fillna(df1).astype(int)

Out[89]:
   A  B  C  D
0  0  1  0  0
1  1  2  0  0
2  2  0  1  3
3  2  4  2  4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.