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

如何为小时数据新增HourType时段分组列(Morning/Evening/Night)

实现小时时段分组并新增HourType列的方法

以下是几种常用工具的实现方案,均遵循你指定的规则:

  • 5至12 → "Morning"
  • 13至20 → "Evening"
  • 21至4(含0、1、2、3、4、21、22、23)→ "Night"

Python(Pandas)

可以用numpy.select实现多条件判断,逻辑清晰易读:

import pandas as pd
import numpy as np

# 读取数据集(示例)
df = pd.read_csv("your_data.csv")

# 定义判断条件和对应结果
conditions = [
    (df["Hours"].between(5, 12)),
    (df["Hours"].between(13, 20)),
    (df["Hours"].between(21, 23) | df["Hours"].between(0, 4))
]
choices = ["Morning", "Evening", "Night"]

# 新增HourType列
df["HourType"] = np.select(conditions, choices, default="Night")

也可以用pd.cut,先处理跨天的Night区间:

# 把0-4的小时映射为24-28,便于连续分组
df["adjusted_hour"] = df["Hours"].apply(lambda x: x + 24 if x <=4 else x)
# 执行分组
df["HourType"] = pd.cut(
    df["adjusted_hour"],
    bins=[0, 12, 20, 28],
    labels=["Morning", "Evening", "Night"],
    include_lowest=True
)
# 可选:删除临时辅助列
df.drop("adjusted_hour", axis=1, inplace=True)

SQL

用CASE WHEN语句直接在查询中生成新列,适用于数据库中的数据集:

SELECT 
    Year,
    Hours,
    Users,
    CASE
        WHEN Hours BETWEEN 5 AND 12 THEN 'Morning'
        WHEN Hours BETWEEN 13 AND 20 THEN 'Evening'
        ELSE 'Night' -- 自动覆盖21-23和0-4的所有情况
    END AS HourType
FROM your_table;

Excel

用嵌套IF函数实现,假设Hours列在B列,在D2单元格输入公式后下拉填充:

=IF(AND(B2>=5,B2<=12),"Morning",IF(AND(B2>=13,B2<=20),"Evening","Night"))

如果使用Excel 365及以上版本,可改用SWITCH函数简化写法:

=SWITCH(TRUE,AND(B2>=5,B2<=12),"Morning",AND(B2>=13,B2<=20),"Evening",TRUE,"Night")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:01:07