从10秒数据计算多时长移动平均:起止时间设置及代码报错求助
解答你的移动平均计算与代码报错问题
Hey there! Let's tackle your two main questions one by one—setting up time windows for moving averages and fixing that DatetimeIndex error.
一、移动平均的时间窗口与起止时间设置
首先,你的数据是10秒采样一次,我们可以直接通过样本数量来定义移动窗口:
- 15分钟窗口:15分钟 = 900秒,900/10 = 90个样本 → 对应
rolling(window=90) - 8小时窗口:8小时 = 28800秒,28800/10 = 2880个样本 → 对应
rolling(window=2880) - 24小时窗口:24小时 = 86400秒,86400/10 = 8640个样本 → 对应
rolling(window=8640)
关于起止时间:
- 如果要计算全数据集的移动平均,不需要额外设置起止时间,
rolling会自动从第一个满足窗口大小的样本开始计算(前89个样本会返回NaN,从第90个开始有有效值)。 - 如果只想计算特定时间段内的移动平均,建议先筛选时间范围,再做移动平均计算(这样更高效)。比如你提到的2019-05-31到2019-07-04,可以用
loc筛选日期范围,或者用between_time筛选每日的时间区间。
二、修复TypeError: Index must be DatetimeIndex错误
你的代码报错的核心原因有两个:
- 你没有将
RecTime列转换为datetime类型,直接设置为索引后不是DatetimeIndex; set_index返回的是新的DataFrame,你没有把结果赋值回Gas_432,导致原DataFrame的索引还是默认的数字索引,无法使用between_time。
正确的代码步骤
import pandas as pd # 1. 先把RecTime列转换成datetime类型(关键!确保时间格式正确) Gas_432['RecTime'] = pd.to_datetime(Gas_432['RecTime']) # 2. 将RecTime设置为DataFrame的索引,并覆盖原数据 Gas_432 = Gas_432.set_index('RecTime') # 3. 筛选你需要的时间范围(示例:2019-05-31 00:00:00 到 2019-07-04 08:08:21) # 用loc筛选日期范围更直观,适合跨多天的情况 filtered_data = Gas_432.loc['2019-05-31 00:00:00':'2019-07-04 08:08:21'] # 4. 计算不同维度的移动平均 ma_15min = filtered_data.rolling(window=90).mean() # 15分钟移动平均 ma_8h = filtered_data.rolling(window=2880).mean() # 8小时移动平均 ma_24h = filtered_data.rolling(window=8640).mean() # 24小时移动平均
额外说明
- 如果你的
RecTime列已经是datetime类型,第一步可以跳过,但建议还是加上pd.to_datetime做校验,避免格式问题。 between_time更适合筛选每日固定时间段的数据(比如每天的08:00到18:00),如果是跨多天的完整时间范围,用loc更方便。
内容的提问来源于stack exchange,提问作者D.Banerjee
相关产品推荐
相关产品推荐

