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:

なぜこれをやりたいのかを少し明確にするために、毎日のタイムステップで計算するモデルがあります。現在の日を表す日時オブジェクトであるモデルに変数があります。いくつかの時系列に対して現在の日を確認する必要があります。その中には完全な日付 (年/月/日) があるものもあれば、月しかないものもあります。時系列/プロファイルは実行時にユーザーによって提供されるため、インデックス作成と同じくらいシームレスなものを望んでいました。TimeSeries オブジェクトのメソッドをオーバーライドしてみました__getitem__(舞台裏の年を修正できるようにするため) が、ちょっとクレイジーなハックのようです。

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 に答える