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
0 1 1.0 1.0
1 1 NaN NaN
2 3 5.0 5.0
3 3 NaN NaN
4 3 9.0 5.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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…