能否用xhistogram创建循环分箱?本地时间分箱实现咨询
关于xhistogram跨零点分箱的实现方案
xhistogram本身不支持直接定义左边界大于右边界的分箱,它默认要求分箱区间是左≤右的有序范围,直接传入左大右小的bins会导致数据无法被正确统计甚至报错。不过可以通过两种简单的方法实现你要的跨零点分箱需求:
方法一:时间偏移法
把跨零点时段的时间值做偏移,让原本的0-1小时变成24-25小时,这样就能用常规的有序分箱来覆盖23-25小时(对应原时间的23-1点),统计完成后再修正分箱标签即可。
示例代码:
import xhistogram as xh import numpy as np # 模拟0-23小时的时间数据 time_data = np.array([23.5, 0.2, 0.8, 2.1, 22.9, 0.5]) # 对0-1点的时间加24小时,实现偏移 shifted_time = np.where(time_data < 1, time_data + 24, time_data) # 定义分箱:23-25对应原时间23-1点,其余按2小时宽度设置常规分箱 bins = [23, 25, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23] hist = xh.histogram(shifted_time, bins=bins) # 修正分箱标签,还原成原时间范围 corrected_bin_labels = [] for left, right in zip(hist.bins[0][:-1], hist.bins[0][1:]): if left == 23 and right == 25: corrected_bin_labels.append("23-1") elif left >= 24: corrected_bin_labels.append(f"{left-24:.0f}-{right-24:.0f}") else: corrected_bin_labels.append(f"{left:.0f}-{right:.0f}") # 输出结果 print("统计频次:", hist.values) print("分箱标签:", corrected_bin_labels)
方法二:掩码筛选+合并统计
直接用掩码筛选出跨零点区间的样本并统计数量,再单独用xhistogram处理其余常规分箱,最后把两部分结果合并。这种方法逻辑更直观,适合分箱规则简单的场景。
示例代码:
import xhistogram as xh import numpy as np time_data = np.array([23.5, 0.2, 0.8, 2.1, 22.9, 0.5]) # 统计跨零点区间(23, 1)的样本数量 midnight_bin_count = np.sum((time_data > 23) | (time_data < 1)) # 处理其余常规2小时分箱(从2点开始到23点) regular_bins = np.arange(2, 25, 2) regular_hist = xh.histogram(time_data, bins=regular_bins) # 合并统计结果和分箱标签 all_counts = np.concatenate([[midnight_bin_count], regular_hist.values]) all_bin_labels = ["23-1"] + [f"{b}-{regular_bins[i+1]}" for i, b in enumerate(regular_bins[:-1])] # 输出结果 print("统计频次:", all_counts) print("分箱标签:", all_bin_labels)
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

