我应该在Pandas中使用什么表示来确保整个时间间隔内的数据有效?

时间:2013-01-07 14:41:14

标签: python pandas time-series

我有一系列小时价格。每个价格在整个1小时内有效。 在Pandas中代表这些价格的最佳方式是什么,这样我就可以在任意更高的频率(如分钟或秒)中对它们进行索引并对它们进行算术运算?

数据细节

样品价格可能是:

>>> prices = Series(randn(5), pd.date_range('2013-01-01 12:00', periods = 5, freq='H'))
>>> prices
2013-01-01 12:00:00   -1.001692
2013-01-01 13:00:00   -1.408082
2013-01-01 14:00:00   -0.329637
2013-01-01 15:00:00    1.005882
2013-01-01 16:00:00    1.202557
Freq: H

现在,如果我想要13:37:42处的值,我会使用什么表示形式(我希望它与13:00相同)?

>>> prices['2013-01-01 13:37:42']
...
KeyError: <Timestamp: 2013-01-01 13:37:42>

重采样

我知道我可以重新计算价格并填写详细信息(ffill,对吗?),但这似乎不是一个很好的解决方案,因为我必须假设我要去的频率将索引编入索引并减少可读性,因为有太多不必要的数据点。

时间跨度

乍一看PeriodIndex似乎有用

>>> price_periods = prices.to_period()
>>> price_periods['2013-01-01 13:37:42']
-1.408082

但是,时间跨度系列不提供我期望从Series获得的一些其他功能。假设我有另一个系列amounts,说明我在某个时刻购买了多少件物品。如果我想计算价格,我想要将两个系列相乘'

>>> amounts = Series([1,2,2], pd.DatetimeIndex(['2013-01-01 13:37', '2013-01-01 13:57', '2013-01-01 14:05']))
>>> amounts*price_periods

但是这会产生异常,有时甚至会冻结我的IPy笔记本。索引也无济于事。

>>> ts_periods[amounts.index]

PeriodIndex结构是否仍在进行中,或者这些功能是否会被添加?是否可能有一些我应该使用的其他结构(或者现在应该在PeriodIndex成熟之前使用)?我正在使用Pandas版本0.9.0.dev-1e68fd9

1 个答案:

答案 0 :(得分:3)

检查asof

prices.asof('2013-01-01 13:37:42')

返回上一个可用日期时间的值:

prices['2013-01-01 13:00:00']

要进行计算,您可以使用:

prices.asof(amounts.index) * amounts

返回具有金额索引和相应值的系列:

>>> prices
2013-01-01 12:00:00    0.943607
2013-01-01 13:00:00   -1.019452
2013-01-01 14:00:00   -0.279136
2013-01-01 15:00:00    1.013548
2013-01-01 16:00:00    0.929920

>>> prices.asof(amounts.index)
2013-01-01 13:37:00   -1.019452
2013-01-01 13:57:00   -1.019452
2013-01-01 14:05:00   -0.279136

>>> prices.asof(amounts.index) * amounts
2013-01-01 13:37:00   -1.019452
2013-01-01 13:57:00   -2.038904
2013-01-01 14:05:00   -0.558272