使用Pandas按Object与State分组实现多列数据分箱并统计样本数及概率
解决方案:按车辆对象和维护类型分箱统计维护时长与间隔
我会用Python的pandas库来实现你需要的分箱统计功能,这个工具处理表格数据和分组计算非常高效,而且分箱规则可以灵活配置。
步骤1:准备数据与定义分箱规则
首先我们先加载你的原始数据,然后定义可配置的分箱区间——你可以根据需求随时调整这些区间的大小、最小值和最大值。
import pandas as pd # 加载原始数据 data = pd.DataFrame({ 'Object': ['A', 'A', 'A', 'A', 'B', 'C', 'C', 'C'], 'state': [1, 1, 1, 2, 1, 1, 2, 2], 'duration_hours': [0.06, 0.87, 1.5, 18, 7, 0.3, 3, 4], 'interval_hours': [0, 34, 80, 0, 0, 0, 0, 12] }) # 定义分箱规则:键是字段名,值是分箱区间(可以根据需求修改) bin_config = { 'duration_hours': [0, 1, 5, 20], # 分箱区间:[0,1), [1,5), [5,20) 'interval_hours': [-1, 50, 100] # 分箱区间:[-1,50), [50,100) }
步骤2:实现分组分箱与统计逻辑
接下来我们编写一个函数,对每个Object+state的分组,分别处理两个字段的分箱,计算每个分箱的样本数和概率:
def calculate_bin_stats(group, bin_config): results = [] total_samples = len(group) # 遍历每个需要分箱的字段 for col, bins in bin_config.items(): # 对当前字段进行分箱,include_lowest确保左区间包含边界值 group['bin'] = pd.cut(group[col], bins=bins, include_lowest=True) # 统计每个分箱的样本数,并按区间顺序排序 bin_counts = group['bin'].value_counts().sort_index() # 转换为结果格式,计算概率(保留两位小数) for bin_range, count in bin_counts.items(): probability = round(count / total_samples, 2) results.append({ 'Object': group['Object'].iloc[0], 'State': group['state'].iloc[0], 'Metric': col, 'Bins': bin_range, 'Data sample': count, '概率': probability }) return pd.DataFrame(results) # 按Object和state分组,应用统计函数 final_result = data.groupby(['Object', 'state']).apply(calculate_bin_stats, bin_config=bin_config).reset_index(drop=True)
步骤3:查看输出结果
运行上述代码后,final_result就是符合你需求的统计表格,比如对于Object A、State 1的部分结果如下:
| Object | State | Metric | Bins | Data sample | 概率 |
|---|---|---|---|---|---|
| A | 1 | duration_hours | [0.0, 1.0) | 2 | 0.67 |
| A | 1 | duration_hours | [1.0, 5.0) | 1 | 0.33 |
| A | 1 | interval_hours | [-1.0, 50.0) | 2 | 0.67 |
| A | 1 | interval_hours | [50.0, 100.0) | 1 | 0.33 |
你可以通过修改bin_config里的区间值,轻松调整分箱的大小、最小值和最大值,适配不同的统计需求。
内容的提问来源于stack exchange,提问作者Pranav Arora
相关产品推荐
相关产品推荐

