colibro
colibro

Reputation: 45

Pandas DataFrame update cell values from second DataFrame

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?

Upvotes: 2

Views: 113

Answers (1)

mozway
mozway

Reputation: 260315

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

Upvotes: 1

Related Questions