如何将列均值存储为变量?解决数据清洗赋值兼容报错问题
问题解答
针对疑问1:可以通过提取数值解决问题
你当前用agg({'LotFrontage': ['mean']})得到的是带列层级的(1,1) DataFrame,直接赋值给单个单元格会触发索引不兼容错误。要把均值存储为单一数值(整数/浮点数),有两种可行方式:
方式1:直接计算均值(推荐)
跳过agg,直接对筛选后的LotFrontage列调用.mean(),得到的就是单个数值:
z = train.loc[ (train.MSSubClass == 190) & (train.MSZoning == 'RL') & (train.LotShape == 'IR1'), 'LotFrontage' # 直接指定列,避免返回整行DataFrame ].mean() # 如需转为整数,用int()或round()处理 z = int(z) # 或者 z = round(z) 保留四舍五入的整数 a.loc[335, 'LotFrontage'] = z # 用.loc赋值更规范,避免潜在警告
方式2:从现有DataFrame提取数值
如果要保留原有的agg写法,可以通过索引提取底层数值:
z = train.loc[ (train.MSSubClass == 190) & (train.MSZoning == 'RL') & (train.LotShape == 'IR1') ].agg({'LotFrontage': ['mean']}).iloc[0, 0] # 转整数 z = int(z) a.loc[335, 'LotFrontage'] = z
针对疑问2:批量填充缺失值的替代方案
如果你的需求是批量填充所有符合条件的LotFrontage缺失值(而非单个行),推荐用.loc精准定位目标行后赋值,避免链式索引的潜在问题:
# 先计算目标分组的LotFrontage均值 mean_lot_frontage = train.loc[ (train.MSSubClass == 190) & (train.MSZoning == 'RL') & (train.LotShape == 'IR1'), 'LotFrontage' ].mean() # 定位a中符合条件且LotFrontage缺失的行,填充均值 a.loc[ (a.MSSubClass == 190) & (a.MSZoning == 'RL') & (a.LotShape == 'IR1') & (a.LotFrontage.isna()), 'LotFrontage' ] = mean_lot_frontage
补充说明
- 优先用
a.loc[行索引, 列名]的方式赋值,避免a.LotFrontage[335]这种链式索引,能规避SettingWithCopyWarning。 - 如果计算均值时目标分组全为NaN,
mean()会返回NaN,此时可根据需求用全局均值、中位数等兜底。
内容的提问来源于stack exchange,提问作者P-Sides
相关产品推荐
相关产品推荐

