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

Python中按日期分组并使用指定分箱聚合分数数据

按日期分组并自定义分箱聚合DataFrame

问题背景

现有两个DataFrame:

  1. 日期-分数数据集:
date   score
2022-12-01   0.28
2022-12-01   0.12
2022-12-01   0.36
2022-12-01   0.42
2022-12-01   0.33
2022-12-02   0.15
2022-12-03   0.23
2022-12-03   0.25
  1. 分箱断点数据集:
breakpoints
0.1
0.2
0.3
0.4
0.5

分箱规则:断点0.1代表所有≤0.1的数值,其余断点以此类推。需要按日期分组,用指定分箱完成聚合,得到如下格式的结果:

breakpoints   2022-12-01   2022-12-02   2022-12-03
0.1            0            0            0
0.2            1            1            0
0.3            1            0            2
0.4            2            0            0
0.5            0            0            0

解决方案

方法一:Pandas cut + 交叉表实现

1. 构造示例数据

import pandas as pd

# 日期-分数数据集
df_scores = pd.DataFrame({
    'date': ['2022-12-01']*5 + ['2022-12-02'] + ['2022-12-03']*2,
    'score': [0.28, 0.12, 0.36, 0.42, 0.33, 0.15, 0.23, 0.25]
})

# 分箱断点数据集
df_breaks = pd.DataFrame({'breakpoints': [0.1, 0.2, 0.3, 0.4, 0.5]})
breaks = df_breaks['breakpoints'].tolist()

2. 对分数按自定义断点分箱

构造包含负无穷的分箱区间,确保所有数值都能被匹配,同时用断点值作为分箱标签:

# 构造分箱区间:[-inf, 0.1], (0.1, 0.2], ..., (0.4, 0.5]
bins = [-float('inf')] + breaks
# 分箱并指定标签
df_scores['bin'] = pd.cut(df_scores['score'], bins=bins, labels=breaks, include_lowest=True)

3. 生成交叉表并对齐断点

用交叉表统计每个日期各分箱的数量,再重新索引确保所有断点都存在,缺失值填充为0:

# 生成日期与分箱的计数交叉表
cross_tab = pd.crosstab(df_scores['bin'], df_scores['date'])
# 对齐所有断点,填充缺失计数为0
result = cross_tab.reindex(breaks).fillna(0).astype(int)
# 重置索引为breakpoints列
result = result.reset_index().rename(columns={'index': 'breakpoints'})

执行后打印result即可得到目标格式的DataFrame。


方法二:结合numpy.histogram与分组apply

如果坚持用numpy.histogram,可以通过groupby.apply实现分组统计:

import numpy as np

def count_bins(group):
    # 对每组分数计算分箱计数
    counts, _ = np.histogram(group['score'], bins=bins)
    return pd.Series(counts, index=breaks)

# 分组计算后转置并整理格式
result_hist = df_scores.groupby('date').apply(count_bins).T.reset_index().rename(columns={'index': 'breakpoints'})

此方法输出结果与方法一完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 10:25:18