看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)现有一条按 1 小时 采样的温度序列,需要把整条时间轴向后平移 30 分钟(与采样频率不同),观察平移效果。
源数据如下:
import pandas as pd
idx = pd.date_range('2023-09-01 08:00', periods=4, freq='h')
s = pd.Series([18.0, 19.5, 21.0, 20.2], index=idx, name='temp')
print(s)
输出:
2023-09-01 08:00:00 18.0
2023-09-01 09:00:00 19.5
2023-09-01 10:00:00 21.0
2023-09-01 11:00:00 20.2
Freq: H, Name: temp, dtype: float64
要求:
shift(freq='30min')
将索引整体向后平移 30 分钟(与原始频率 1 小时不一致)。期望结果:
2023-09-01 08:30:00 18.0
2023-09-01 09:30:00 19.5
2023-09-01 10:30:00 21.0
2023-09-01 11:30:00 20.2
Freq: 30T, Name: temp, dtype: float64
代码如下:
import pandas as pd
idx = pd.date_range('2023-09-01 08:00', periods=4, freq='h')
s = pd.Series([18.0, 19.5, 21.0, 20.2], index=idx, name='temp')
# 向后平移 30 分钟(与采样频率不同)
shifted = s.shift(freq='30min')
print(shifted)
输出:
2023-09-01 08:30:00 18.0
2023-09-01 09:30:00 19.5
2023-09-01 10:30:00 21.0
2023-09-01 11:30:00 20.2
Freq: 30T, Name: temp, dtype: float64
shift(freq='30min')
按绝对时间偏移量整体移动索引,与原始采样频率无关,因此可轻松实现“异频”平移,同时保持数据值不变。
(完)
更新时间:2025-09-14 15:07:29 标签:pandas python 时间 移动