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

按列分组数据:按小时聚合total列并生成独立小时列

实现按小时分组求和并转成宽格式列

嘿,我来帮你搞定这个需求!你想要把按hora(小时)列分组求和后的结果,从行形式转换成每个小时单独一列的宽格式对吧?下面用两种常用的数据分析工具给你演示具体实现:

方法一:使用R语言(tidyverse工具包)

我们可以用dplyr做分组求和,再用tidyr的pivot_wider函数转成宽格式:

# 加载所需工具包
library(tidyverse)

# 先构建你的数据集(如果已有数据框可跳过这步)
df <- tibble(
  id_tecnico = rep("0011ab4f-6871-40f4-91f2-818e309baa41", 10),
  dia = c(8,45,46,50,58,70,81,86,89,92),
  hora = c(13,10,9,14,12,12,11,11,9,11),
  total = rep(1,10)
)

# 核心步骤:分组求和 → 转宽格式
result <- df %>%
  # 按小时分组,计算total的总和
  group_by(hora) %>%
  summarise(total_sum = sum(total), .groups = "drop") %>%
  # 将每个小时转为列,列名前缀为hour,缺失的小时填充0
  pivot_wider(
    names_from = hora,
    names_prefix = "hour",
    values_from = total_sum,
    values_fill = 0
  )

# 查看结果
print(result)

运行后你会得到这样的结果:

A tibble: 1 × 6

hour9 hour10 hour11 hour12 hour13 hour14

1 2 1 3 2 1 1

方法二:使用Python(pandas库)

用pandas的groupby做分组求和,再通过pivot转成宽格式:

import pandas as pd

# 构建你的数据集(如果已有DataFrame可跳过这步)
data = {
    "id_tecnico": ["0011ab4f-6871-40f4-91f2-818e309baa41"]*10,
    "dia": [8,45,46,50,58,70,81,86,89,92],
    "hora": [13,10,9,14,12,12,11,11,9,11],
    "total": [1]*10
}
df = pd.DataFrame(data)

# 核心步骤:分组求和 → 转宽格式 → 重命名列
# 1. 按小时分组求和
sum_by_hour = df.groupby("hora")["total"].sum().reset_index()
# 2. 转成宽格式,缺失值填充0
wide_result = sum_by_hour.pivot(columns="hora", values="total").fillna(0)
# 3. 给列名加上hour前缀
wide_result.columns = [f"hour{col}" for col in wide_result.columns]
# 4. 重置索引让结果更整洁
wide_result = wide_result.reset_index(drop=True)

# 查看结果
print(wide_result)

运行后输出的结果类似:

hour9 hour10 hour11 hour12 hour13 hour14
0 2.0 1.0 3.0 2.0 1.0 1.0

内容的提问来源于stack exchange,提问作者Cristhian Silva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:39:58