是否可以resample在不规则间隔的数据上使用?(我知道文档说它是为了“重新采样常规时间序列数据”,但我想尝试一下它是否也适用于不规则数据。也许它没有,或者我做错了什么。)
在我的真实数据中,我通常每小时有 2 个样本,它们之间的时间差通常在 20 到 40 分钟之间。所以我希望将它们重新采样为定期的每小时系列。
为了测试我是否正确使用它,我使用了一些我已经拥有的随机日期列表,因此它可能不是最好的例子,但至少适用于它的解决方案将非常强大。这里是:
fraction number time
0 0.729797 0 2014-10-23 15:44:00
1 0.141084 1 2014-10-30 19:10:00
2 0.226900 2 2014-11-05 21:30:00
3 0.960937 3 2014-11-07 05:50:00
4 0.452835 4 2014-11-12 12:20:00
5 0.578495 5 2014-11-13 13:57:00
6 0.352142 6 2014-11-15 05:00:00
7 0.104814 7 2014-11-18 07:50:00
8 0.345633 8 2014-11-19 13:37:00
9 0.498004 9 2014-11-19 22:47:00
10 0.131665 10 2014-11-24 15:28:00
11 0.654018 11 2014-11-26 10:00:00
12 0.886092 12 2014-12-04 06:37:00
13 0.839767 13 2014-12-09 00:50:00
14 0.257997 14 2014-12-09 02:00:00
15 0.526350 15 2014-12-09 02:33:00
Run Code Online (Sandbox Code Playgroud)
现在我想每月重新采样这些:
df_new = df.set_index(pd.DatetimeIndex(df['time']))
df_new['fraction'] = df.fraction.resample('M',how='mean')
df_new['number'] = df.number.resample('M',how='mean')
Run Code Online (Sandbox Code Playgroud)
但我明白了TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'- 除非我在分配日期时间索引时做错了什么,它一定是由于不规则?
所以我的问题是:
(我只看到一个解决方案,即首先重新索引数据以获得更精细的间隔,在两者之间插入值,然后将其重新索引为每小时间隔。如果是这样,那么很快就会出现一个有关重新索引的正确实现的问题。)
您不需要显式使用DatetimeIndex,只需设置'time'为索引,pandas 就会处理其余的事情,只要您的列已使用或其他方法'time'转换为日期时间。pd.to_datetime此外,如果您使用相同的方法,则无需单独对每列重新采样;只需在整个 DataFrame 上执行即可。
# Convert to datetime, if necessary.
df['time'] = pd.to_datetime(df['time'])
# Set the index and resample (using month start freq for compact output).
df = df.set_index('time')
df = df.resample('MS').mean()
Run Code Online (Sandbox Code Playgroud)
结果输出:
fraction number
time
2014-10-01 0.435441 0.5
2014-11-01 0.430544 6.5
2014-12-01 0.627552 13.5
Run Code Online (Sandbox Code Playgroud)