'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?
Solution 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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mozway |
