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

如何将Pandas DataFrame行按列值均匀分配至小时时间戳

解决方法

核心思路

针对每行数据,根据Execution的数值生成对应数量的连续小时时间戳,再将这些时间戳拆分成独立行,每行的Execution固定为1;Execution为1的行直接保留原时间戳即可。

代码实现

import pandas as pd

# 替换为你的实际DataFrame
df = pd.DataFrame({
    'DateTime': ['2023-04-03 07:00:00', '2023-04-03 10:00:00', '2023-04-03 12:00:00', '2023-04-03 14:00:00', '2023-04-03 18:00:00'],
    'Execution': [4, 1, 1, 1, 1]
})

# 1. 确保DateTime列是datetime类型
df['DateTime'] = pd.to_datetime(df['DateTime'])

# 2. 为每行生成对应数量的连续小时时间序列
df['DateTime'] = df.apply(
    lambda row: pd.date_range(start=row['DateTime'], periods=row['Execution'], freq='H'),
    axis=1
)

# 3. 展开时间序列为独立行,重置索引并统一Execution值为1
result_df = df.explode('DateTime').reset_index(drop=True)
result_df['Execution'] = 1

print(result_df)

代码说明

  • 先转换DateTime列类型为datetime,保证时间运算的合法性;
  • 用pd.date_range生成连续小时:比如Execution=4时,会从7:00开始生成4个连续小时的时间戳;
  • 通过explode把每行的时间序列拆成单独行,最后统一设置Execution为1,得到预期格式的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 13:12:25