python - 我想使用 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值
解决方案
创建数据
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
推荐阅读
- oracle-apex - 从计算中绑定标签 - oracle apex
- javascript - 将此数组中的数字替换为 %
- arrays - 使用C中的数组打印二维二叉树
- python - pip 可以在指定的本地目录中安装第一个搜索轮然后再安装 pypi 吗?
- r - 用新变量对不同时期进行分组
- api - 带有 curl 的 LinkedIn API?
- spring-boot - 如何在spring boot rest api中使用postman将带有一些变量的图像上传到mysql
- linux - cmake交叉编译链接提升
- google-apps-script - 匹配 X 的出现是 Y 但对应的 Z 缺失
- algorithm - 计算置换子集