python - 基于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
解决方案
推荐阅读
- javascript - 在 jQuery 中使用 this 作为事件处理程序切换类
- java - 有没有办法在不从 Java 路径中读取文件的情况下提供文件下载?
- splunk - 如何通过 HTTP 向 Splunk 提供指标?
- python - 元组索引超出范围 (sqlfluff)
- python - 如何找到股票每个交易日的低点?
- javascript - 如何正则表达式用空格替换文本中的所有点但排除网址?
- node.js - 如何使用节点 js 以与平台无关的方式更新 PATH 变量
- java - 没有 SpringBoot 的 Spring 缓存 Caffeine 集成
- visual-studio - 如何使用带有 WSL 2 的 Visual Studio 调试我的 .NET Core 单元测试?
- html - 加载“allow-from https”时遇到无效的“X-Frame-Options”标头不是可识别的指令。标题将被忽略