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

时间:2016-12-13 00:52:43

标签: python pandas

是否可以在不规则间隔的数据上使用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' - 除非我在分配日期时间索引时出错了,否则必然是由于不规则性?

所以我的问题是:

  1. 我正确使用它吗?
  2. 如果1 == True,是否没有直接的方法来重新采样数据?
  3. (我只看到一个解决方案,首先重新索引数据以获得更精细的间隔,在两者之间插入值,然后将其重新索引到每小时间隔。如果是这样,那么关于正确实施reindex的问题将很快出现。 )

1 个答案:

答案 0 :(得分:2)

您不需要明确使用DatetimeIndex,只需设置'time'作为索引,只要您的'time'列已经过了,pand就会处理其余内容使用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
相关问题