当我重新采样 Pandas 时间序列以减少数据点数量时,每个结果数据点的时间戳位于每个重新采样箱的开头。当以不同的重采样率过度绘制图形时,这会导致数据的明显偏移。无论重采样率如何,如何将重采样数据的时间戳“居中”在其 bin 中?
我现在得到的是(重新采样到一小时时):
In [12]: d_r.head()
Out[12]:
2017-01-01 00:00:00 0.330567
2017-01-01 01:00:00 0.846968
2017-01-01 02:00:00 0.965027
2017-01-01 03:00:00 0.629218
2017-01-01 04:00:00 -0.002522
Freq: H, dtype: float64
Run Code Online (Sandbox Code Playgroud)
我想要的是:
In [12]: d_r.head()
Out[12]:
2017-01-01 00:30:00 0.330567
2017-01-01 01:30:00 0.846968
2017-01-01 02:30:00 0.965027
2017-01-01 03:30:00 0.629218
2017-01-01 04:30:00 -0.002522
Freq: H, dtype: float64
Run Code Online (Sandbox Code Playgroud)
MWE 显示明显转变:
#!/usr/bin/env python3
Minimal working example:
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
import seaborn
seaborn.set()
plt.ion()
# sample data
t = pd.date_range('2017-01-01 00:00', '2017-01-01 10:00', freq='1min')
d = pd.Series(np.sin(np.linspace(0, 7, len(t))), index=t)
d_r = d.resample('1h').mean()
d.plot()
d_r.plot()
Run Code Online (Sandbox Code Playgroud)
只添加 30 分钟的 timedelta 到索引怎么样?
df.index = df.index + datetime.timedelta(minutes=30)
Run Code Online (Sandbox Code Playgroud)