pandas处理15分钟间隔Sdate列时丢失分钟及数据缺失问题咨询
问题原因分析
该问题和pd.to_datetime没有关联,是小时分组逻辑错误导致的。
小时间隔的原始数据中,每个小时仅对应唯一的Sdate时间戳,因此直接对Sdate分组会天然按小时聚合,看起来运行正常。而15分钟间隔的原始数据中,每个小时对应4个不同的时间戳,直接对完整时间戳分组会得到15分钟粒度的分组结果,不符合小时聚合的需求,若后续逻辑直接按小时条数取值就会出现数据丢失的问题。
解决方案
- 首先建议显式指定
pd.to_datetime的解析格式,避免自动解析出现日期/月份顺位识别错误:
import pandas as pd import numpy as np list_ = [] for file_ in allFiles: df = pd.read_csv(file_, index_col=None, header=0, low_memory=False) # 若实际日期格式为月/日/年,将format改为'%m/%d/%Y %H:%M'即可 df['Sdate'] = pd.to_datetime(df['Sdate'], format='%d/%m/%Y %H:%M') df.reset_index(drop=True, inplace=True) list_.append(df) # 合并所有文件数据 full_df = pd.concat(list_, ignore_index=True)
- 第二步修改分组逻辑,先将时间戳截断到小时粒度再分组:
# 按小时粒度截断时间列后分组 grouped = full_df.groupby(full_df['Sdate'].dt.floor('H')) # 聚合逻辑保持不变 hourly = grouped.aggregate(np.sum).reset_index()
如果需要保留年、月、日、小时单独的字段做后续分析,也可以提前拆解时间列后分组:
full_df['date'] = full_df['Sdate'].dt.date full_df['hour'] = full_df['Sdate'].dt.hour grouped = full_df.groupby(['date', 'hour']) hourly = grouped.aggregate(np.sum).reset_index()
内容的提问来源于stack exchange,提问作者Bloggs
相关产品推荐
相关产品推荐

