You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按type类别中位数填充sensor3列无效负值的实现需求

按类别中位数填充传感器无效值

原始数据集

import pandas as pd

df = pd.DataFrame(
{'sensor1': [1.94,0.93,0.98,1.75,1.75,3.25,0.5,0.5,5.59,6.02,9.21,4.54,3.71,1.05],
 'sensor2': [-0.91,0.42,-0.11,0.0,0.0,-0.12,0.0,0.0,0.48,0.26,-1.5,-0.75,-1.45,0.06],
 'sensor3': [18,19,20,-2094,-2094,17,17,17,-985,-985,1163,1163,1163,-1265],
 'type': [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3]}
)

# 查看前5行数据
df.head()

输出:

sensor1  sensor2  sensor3  type
0     1.94    -0.91       18     1
1     0.93     0.42       19     1
2     0.98    -0.11       20     1
3     1.75     0.00    -2094     1
4     1.75     0.00    -2094     1

需求说明

sensor3列中的负值为无效数据,需要用对应type类别下sensor3有效值的中位数填充所有无效值,预期处理后的结果如下:

sensor1  sensor2  sensor3  type
0     1.94    -0.91       18     1
1     0.93     0.42       19     1
2     0.98    -0.11       20     1
3     1.75     0.00       19     1
4     1.75     0.00       19     1
5     3.25    -0.12       17     2
6     0.50     0.00       17     2
7     0.50     0.00       17     2
8     5.59     0.48       17     2
9     6.02     0.26       17     2
10    9.21    -1.50     1163     3
11    4.54    -0.75     1163     3
12    3.71    -1.45     1163     3
13    1.05     0.06     1163     3

解决方案代码

# 计算每个type类别下sensor3有效值的中位数
median_map = df[df['sensor3'] >= 0].groupby('type')['sensor3'].median().to_dict()

# 用中位数填充sensor3的无效值(负值)
df['sensor3'] = df['sensor3'].mask(df['sensor3'] < 0, df['type'].map(median_map))

# 查看处理后的完整数据
print(df)

代码说明

  1. 先筛选出sensor3的有效值(非负值),按type分组计算中位数,将结果转为字典映射关系;
  2. 使用mask方法,批量将sensor3中的负值替换为对应type的中位数;
  3. 该方法无需循环遍历,处理效率更高,适合批量数据操作。

内容的提问来源于stack exchange,提问作者Amina Umar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 20:55:24