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

如何在scikit-learn MinMaxScaler中结合Group by实现分组归一化?

按分组实现MinMaxScaler归一化

问题背景

使用scikit-learn的MinMaxScaler做特征归一化时,现有代码基于全量数据计算min/max,需修改为按a列分组,每个分组内单独计算min/max执行归一化。

原代码(全局归一化)

from sklearn.preprocessing import MinMaxScaler
import pandas as pd

mydict = [{'a': 1, 'b': 2 },
          {'a': 1, 'b': 8 },
          {'a': 1, 'b': 5 },
          {'a': 2, 'b': 6 },
          {'a': 2, 'b': 1 },
          {'a': 2, 'b': 5 }]

df = pd.DataFrame(mydict)

scaler = MinMaxScaler(feature_range=(100,200))
df['x'] = scaler.fit_transform(df[['b']])
print(df)

原输出(全局归一化结果)

a   b           x
0   1   2  114.285714
1   1   8  200.000000
2   1   5  157.142857
3   2   6  171.428571
4   2   1  100.000000
5   2   5  157.142857

期望输出(分组归一化结果)

a   b           x
0   1   2  100.000000
1   1   8  200.000000
2   1   5  157.142857
3   2   6  200.000000
4   2   1  100.000000
5   2   5  152.380952

解决方案:分组应用MinMaxScaler

通过groupby结合自定义函数,对每个分组单独执行归一化操作,代码如下:

from sklearn.preprocessing import MinMaxScaler
import pandas as pd

mydict = [{'a': 1, 'b': 2 },
          {'a': 1, 'b': 8 },
          {'a': 1, 'b': 5 },
          {'a': 2, 'b': 6 },
          {'a': 2, 'b': 1 },
          {'a': 2, 'b': 5 }]

df = pd.DataFrame(mydict)

# 定义分组归一化函数
def scale_group(group):
    scaler = MinMaxScaler(feature_range=(100, 200))
    # 对当前分组的b列做归一化,生成x列
    group['x'] = scaler.fit_transform(group[['b']])
    return group

# 按a列分组,应用归一化函数并合并结果
df = df.groupby('a', group_keys=False).apply(scale_group)
print(df)

代码说明

  • groupby('a'):按a列的值将数据拆分为独立分组
  • group_keys=False:避免分组操作后在结果中添加分组键索引
  • 自定义scale_group函数:对每个分组单独初始化MinMaxScaler,仅基于当前分组的b列数据计算min/max,完成归一化后返回分组数据
  • apply(scale_group):将归一化函数应用到每个分组,自动合并所有分组的结果

运行结果

a   b           x
0   1   2  100.000000
1   1   8  200.000000
2   1   5  157.142857
3   2   6  200.000000
4   2   1  100.000000
5   2   5  152.380952

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 16:10:30