Amit Amit - 2 months ago 10
Python Question

Fill missing values of 1 data frame from another data frame using pandas

Need help in filling 0's.

In the below dataframe i have a column "Item_Visibility" which has zeros. I need to fill those with values from second dataframe(image 2). The common column between the 2 dataframes is "Item_Identifier".

Thanks in advance

enter image description here
enter image description here

Answer

try this:

import pandas as pd
import numpy as np

df = pd.DataFrame({"A":["a", "b", "c", "d", "e"], "B":[1, 2, 0, 0, 0]})
s = pd.Series([10, 20, 30, 40], index=["a", "b", "c", "d"])

mask = df["B"] == 0
df.loc[mask, "B"] = s[df.loc[mask, "A"]].values

df:

   A  B
0  a  1
1  b  2
2  c  0
3  d  0
4  e  0

s:

a    10
b    20
c    30
d    40
dtype: int64

output:

   A     B
0  a   1.0
1  b   2.0
2  c  30.0
3  d  40.0
4  e   NaN