'pandas: fillna with data from another dataframe, based on the same ID and keeping all values
I want to fillna of df1, using df2, based on same colorID while keeping all rows and columns of df1.
df1=
colorID age flower
red1 12 sun
red2 na sun
green 23 hydro
red3 na hydro
yellow 3 sun
red4 na hydro
df2=
colorID age
red2 4
blue 5
red3 6
red4 7
desired df3 =
colorID age flower
red1 12 sun
red2 4 sun
green 23 hydro
red3 6 hydro
yellow 3 sun
red4 7 hydro
Tried set_index()
df1.set_index("colorID").age.fillna(df2.set_index("colorID").age).reset_index()
but only colorID and age are the outputs.
Solution 1:[1]
You can pass a DataFrame to the fillna function after setting the index of both the DataFrames to the common field - colorID
df1 = df1.set_index('colorID')
df2 = df2.set_index('colorID')
df1 = df1.fillna(df2)
# age flower
#colorID
#red1 12 sun
#red2 4 sun
#green 23 hydro
#red3 6 hydro
#yellow 3 sun
#red4 7 hydro
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 | Mortz |
