首页 > 解决方案 > 我想使用 fillna 均值来填充缺失值。我想根据产品 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 

我想根据product_id填写product_price列和product_sale列的nan值

标签: pythonpandas

解决方案


创建数据

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

结果:

    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

用分组方法填充 nan

df = df[['product_ID']].join(df.groupby("product_ID")
        .transform(lambda x: x.fillna(x.mean())))
df

结果:

    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

推荐阅读