import pandas as pd
# 创建一个示例 DataFrame
data = {
'时间戳': ['2024-04-01 08:00:00', '2024-04-01 08:20:00', '2024-04-01 08:40:00', '2024-04-01 09:05:00', '2024-04-01 09:20:00'],
'车流量': [150, 165, 160, 170, 180]
}
df = pd.DataFrame(data)
print(df)
df['时间戳'] = pd.to_datetime(df['时间戳']) # 确保时间戳是 datetime 类型
# set_index:
# 通过将 时间戳 列设置为索引,我们可以将 DataFrame 转换为一个以时间为索引的时间序列数据格式。
df.set_index('时间戳', inplace=True) # 设置时间戳为索引
print(df)
# 重新采样并前向填充
resampled_df = df.resample('15T').ffill()
print(resampled_df)
# 将乱序数据,按照15分钟为标准重新划分
输出
时间戳 车流量
0 2024-04-01 08:00:00 150
1 2024-04-01 08:20:00 165
2 2024-04-01 08:40:00 160
3 2024-04-01 09:05:00 170
4 2024-04-01 09:20:00 180
车流量
时间戳
2024-04-01 08:00:00 150
2024-04-01 08:20:00 165
2024-04-01 08:40:00 160
2024-04-01 09:05:00 170
2024-04-01 09:20:00 180
车流量
时间戳
2024-04-01 08:00:00 150
2024-04-01 08:15:00 150
2024-04-01 08:30:00 165
2024-04-01 08:45:00 160
2024-04-01 09:00:00 160
2024-04-01 09:15:00 170
Process finished with exit code 0
总结
-
resample('15T')
:resample
是一个强大的方法,用于将时间序列数据重新采样到一个新的频率。这里的 '15T' 表示每15分钟。这个操作创建了一个重新采样的对象,为每15分钟的时间段定义了一个新的聚合框架。- 注意,
resample
本身不修改数据,它创建了一个可以进一步应用聚合函数的重新采样对象。
-
ffill()
:ffill
或前向填充是一个方法,用于填充重新采样期间可能出现的任何缺失值。如果一个特定的15分钟时间段内没有数据点,ffill
会将最后一个有效观察结果向前填充到当前的空缺位置。