5

使用 pandas,我可以使用 datetime 对象(带有月份和日期)索引时间序列并获取一段时间的值,例如:

from pandas import *
ts = TimeSeries([41,45,48],[Period('2012'),Period('2013'),Period('2014')])
print ts[datetime(2013,05,17)]

有没有办法定义一个有一个月但没有一年的时期?我有一个每月频率的平均年度概况,我希望能够按月/日编制索引,例如:

ts = TimeSeries(range(1,13),[Period(month=n,freq='M') for n in range(1,13)])
print ts[datetime(2013,05,17)]

Period 对象似乎不支持这一点(它会引发错误)。有没有比用年份创建时间序列更好的方法,然后在用于索引时间序列之前修改 datetime 对象?

http://pandas.pydata.org/pandas-docs/dev/timeseries.html#period

编辑1:

澄清一下我为什么要这样做:我有一个按每日时间步长计算的模型。我在模型中有一个变量,它是一个代表当天的日期时间对象。我需要根据几个时间序列检查当前日期,其中一些有一个完整的日期(年/月/日),而另一些只有一个月。我希望像索引一样无缝,因为时间序列/配置文件是由用户在运行时提供的。我已经尝试过重写__getitem__TimeSeries 对象的方法(这样我就可以修复幕后的岁月),但这似乎有点疯狂。

from pandas import *

class TimeSeriesProfile(TimeSeries):
    year = 2004

    def __new__(self, *args, **kwargs):
        inst = TimeSeries.__new__(self, *args, **kwargs)
        inst.index = period_range(str(self.year)+str(inst.index[0])[4:], periods=len(inst.index), freq=inst.index.freq)
        return inst.view(TimeSeriesProfile)

    def __getitem__(self, key):
        without_year = datetime(self.year, key.month, key.day, key.hour, key.minute, key.second)
        return TimeSeries.__getitem__(self, without_year)

ts = TimeSeriesProfile(range(0, 366), period_range('1996-01-01', periods=366, freq='D'))

print ts[datetime(2008, 02, 29)]
4

1 回答 1

1

尝试period_range

In [65]: TimeSeries(range(1, 13), period_range('2013-01', periods=12, freq='M'))
Out[65]: 
2013-01     1   
2013-02     2   
2013-03     3   
2013-04     4   
2013-05     5   
2013-06     6   
2013-07     7   
2013-08     8   
2013-09     9   
2013-10    10  
2013-11    11  
2013-12    12  
Freq: M, dtype: int64
于 2013-05-29T02:19:37.133 回答