2

Say I have two DataFrames: df1 and df2. df2 beeing a subframe of df1. Eg:

df1=pd.DataFrame(index=[0,1,2,3,4],columns=['a','b','c']).fillna(0)

df2=pd.DataFrame([1,2,3],index=[0,2,4],columns=['b'])

Is there a more elegant, implicit version of this:

df1.loc[df2.index,df2.columns]=df2.values

And why would it be preferable?

1 Answer 1

1

You can use update:

df1.update(df2)

The operation is in place (no output), and might change the type of the data.

resulting df1:

   a    b  c
0  0  1.0  0
1  0  0.0  0
2  0  2.0  0
3  0  0.0  0
4  0  3.0  0

A workaround to help getting integer type is to use convert_dtypes on df2:

df1.update(df2.convert_dtypes())

output:

   a  b  c
0  0  1  0
1  0  0  0
2  0  2  0
3  0  0  0
4  0  3  0
Sign up to request clarification or add additional context in comments.

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.