如何在Pandas中添加带连续datetime索引的空/虚拟行?
如何用Pandas为Datetime索引的DataFrame添加连续时间行并填充默认值
问题背景
现有一个以datetime类型为索引(start_time)的DataFrame,希望在现有数据基础上添加连续的datetime行,并将新行的consumption和hour字段设为0或指定虚拟值。
原始DataFrame
consumption hour start_time 2022-09-30 14:00:00+02:00 199.0 14.0 2022-09-30 15:00:00+02:00 173.0 15.0 2022-09-30 16:00:00+02:00 173.0 16.0 2022-09-30 17:00:00+02:00 156.0 17.0 2022-09-30 18:00:00+02:00 142.0 18.0 2022-09-30 19:00:00+02:00 163.0 19.0 2022-09-30 20:00:00+02:00 138.0 20.0 2022-09-30 21:00:00+02:00 183.0 21.0 2022-09-30 22:00:00+02:00 138.0 22.0 2022-09-30 23:00:00+02:00 143.0 23.0
期望输出(修正日期错误:9月无31日,替换为10月1日)
consumption hour start_time 2022-09-30 14:00:00+02:00 199.0 14.0 2022-09-30 15:00:00+02:00 173.0 15.0 2022-09-30 16:00:00+02:00 173.0 16.0 2022-09-30 17:00:00+02:00 156.0 17.0 2022-09-30 18:00:00+02:00 142.0 18.0 2022-09-30 19:00:00+02:00 163.0 19.0 2022-09-30 20:00:00+02:00 138.0 20.0 2022-09-30 21:00:00+02:00 183.0 21.0 2022-09-30 22:00:00+02:00 138.0 22.0 2022-09-30 23:00:00+02:00 143.0 23.0 2022-10-01 00:00:00+02:00 0.0 0.0 2022-10-01 01:00:00+02:00 0.0 1.0
实现方案
方案1:用resample补全连续时间序列
适合需要补全整个时间区间内所有缺失小时的场景:
import pandas as pd # 确保索引为datetime类型(若未转换则执行此步) df.index = pd.to_datetime(df.index) # 按小时重采样,缺失值填充为0 df_resampled = df.resample('H').fillna(0) # 重新生成hour列,匹配对应时间的小时数 df_resampled['hour'] = df_resampled.index.hour
如果需要指定补全的结束时间,可以先构造完整时间索引再重新对齐:
# 构造从原始数据最早时间到目标结束时间的完整小时索引 full_time_idx = pd.date_range( start=df.index.min(), end='2022-10-01 01:00:00+02:00', freq='H' ) # 重新索引并填充缺失值 df_full = df.reindex(full_time_idx, fill_value=0) # 更新hour列 df_full['hour'] = df_full.index.hour
方案2:手动构造新行并追加
适合仅需要添加特定几行的场景:
# 构造需要添加的时间点 new_time_points = pd.date_range( start='2022-10-01 00:00:00+02:00', end='2022-10-01 01:00:00+02:00', freq='H' ) # 构造新行的DataFrame new_rows = pd.DataFrame( data={ 'consumption': 0.0, 'hour': new_time_points.hour }, index=new_time_points ) # 合并原数据与新行 df_combined = pd.concat([df, new_rows])
内容的提问来源于stack exchange,提问作者Naeem
相关产品推荐
相关产品推荐

