首页 > 解决方案 > 基于python中的binning组合找到最小方差

问题描述

我希望在进行分组之前使用循环来遍历对变量进行分箱的所有组合。示例数据:

import pandas as pd
df = pd.DataFrame({'id': [1,2,3,4,5,6,7,8,9,10],
                   'age': [23,54,47,38,37,21,27,72,25,36],
                   'score':[28,38,47,27,37,26,28,48,27,47]})
df.head()

    id  age score
0   1   23  28
1   2   54  38
2   3   47  47
3   4   38  27
4   5   37  37

然后像这样手动创建垃圾箱:

bins = [20,50,70,80]
labels = ['-'.join(map(str,(x,y))) for x, y in zip(bins[:-1], bins[1:])]
df["age_bin"] = pd.cut(df["age"], bins = bins,labels = labels)

最后计算该 bin 组合的平均方差:

df.groupby("age_bin").agg({'score':'var'}).mean()

如何循环遍历所有 bin 组合,最小 bin 大小为 10,但对 bin 的数量没有限制,并假设它们不必是相同的大小?

例如

      bins              mean
0   [20, 50, 70, 80]    82.553571
1   [20, 70, 80]        74.611111
2   [20, 30, 60, 80]    35.058333

标签: pythonpandasbinning

解决方案


推荐阅读