在熊猫中重新采样不规则间隔的数据

杜尔巴希特

是否可以以某种方式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

现在我想每月重新采样一次:

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')

但是我明白了TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'-除非我在分配datetime索引时做错了事,那一定是由于不规则性造成的吗?

所以我的问题是:

  1. 我使用正确吗?
  2. 如果1 == True,是否没有直接的方法可以对数据进行重新采样?

(我只看到一种解决方案,首先为数据重新编制索引以获得更细的间隔,然后插值之间的值,然后将其重新编制为每小时间隔。如果是这样,那么不久就会出现有关正确执行重新编制索引的问题。)

您无需显式使用DatetimeIndex,只需设置'time'为index即可,其余的将由pandas负责,只要您的'time'列已使用pd.to_datetime或其他方法转换为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()

结果输出:

            fraction  number
time                        
2014-10-01  0.435441     0.5
2014-11-01  0.430544     6.5
2014-12-01  0.627552    13.5

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章