Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

python - 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           28                2700.00
   2           25                2400.00
   2           Nan               Nan
   2           27                2600.00 

I want to fill the nan value of product_price column and product_sale column based on product_id

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...