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

如何基于小时区间生成含0/1值的目标DataFrame?

嘿,这个需求我之前也碰到过,用Pandas就能高效解决,不用写繁琐的循环~我给你两种方案,一种适合几千行的大数据量,另一种更直观好理解。

首先先模拟你的原始数据方便演示:

import pandas as pd
import numpy as np

# 模拟你的原始DataFrame
df = pd.DataFrame({
    0: [11, 3, 11, 6, 16],
    1: [12, 4, 12, 7, 16]
})

方案一:高效广播法(推荐几千行数据用这个)

这种方法用Numpy的广播机制,比逐行遍历快很多,处理大数据量更丝滑:

# 定义24小时的列名
hour_columns = list(range(1, 25))

# 把起始、结束小时转成可广播的数组
start_hours = df[0].values[:, np.newaxis]
end_hours = df[1].values[:, np.newaxis]
# 把24小时转成可广播的数组
all_hours = np.array(hour_columns)[np.newaxis, :]

# 判断每个小时是否在区间内,转换为0/1并生成新DataFrame
result_df = pd.DataFrame(
    (all_hours >= start_hours) & (all_hours <= end_hours),
    columns=hour_columns,
    dtype=int
)

方案二:直观apply法(适合小数据量或新手理解)

如果觉得广播有点抽象,用apply逐行处理也可以,逻辑更直白:

hour_columns = list(range(1, 25))

def map_hours(row):
    start, end = row[0], row[1]
    # 对每个小时判断是否在区间内,返回1或0
    return pd.Series([1 if start <= h <= end else 0 for h in hour_columns], index=hour_columns)

# 应用到每一行
result_df = df.apply(map_hours, axis=1)

你可以试试这两种方法,生成的result_df就是你要的24小时列的DataFrame,比如原数据索引1的行(3到4),对应的result_df里3、4列是1,其他都是0,完全符合你的要求~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:39:15