I Want To Use Fillna Mean To Fill The Missing Value. I Want To Do That According To Product Id
product_ID Prodcut_Price Product_monthly_sale 1 24 2000.00 1 Nan 2500.00 1 26 Nan 1
Solution 1:
Create data
df = pd.DataFrame({'product_ID':[1,1,3,3,3],
'Prodcut_Price':[1,np.nan,5,np.nan, 9],
'Product_monthly_sale':[1,np.nan,5,np.nan, 5]})
df
Result:
product_ID Prodcut_Price Product_monthly_sale
011.01.011NaNNaN235.05.033NaNNaN439.05.0
Fill nan with grouped means
df = df[['product_ID']].join(df.groupby("product_ID")
.transform(lambda x: x.fillna(x.mean())))
df
Result:
product_ID Prodcut_Price Product_monthly_sale
0 1 1.0 1.0
1 1 1.0 1.0
2 3 5.0 5.0
3 3 7.0 5.0
4 3 9.0 5.0
Solution 2:
For improve performance avoid lambda function, rather use GroupBy.transform
for means per groups with DataFrame.fillna
:
df=df.fillna(df.groupby("product_ID").transform('mean'))print(df)product_IDProdcut_PriceProduct_monthly_sale0124.02000.01126.02500.02126.02400.03128.02700.04225.02400.05226.02500.06227.02600.0
Post a Comment for "I Want To Use Fillna Mean To Fill The Missing Value. I Want To Do That According To Product Id"