【问题标题】:Creating pandas timeseries with a month but not a year用一个月而不是一年创建熊猫时间序列
【发布时间】:2013-05-23 22:36:50
【问题描述】:

使用 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)]

【问题讨论】:

    标签: python datetime pandas


    【解决方案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
    

    【讨论】:

    • period_range 看起来很有用,但它不能回答我关于创建没有年份的时间序列的基本问题。
    猜你喜欢
    • 2019-12-19
    • 2020-12-09
    • 1970-01-01
    • 2016-06-27
    • 2020-12-14
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    相关资源
    最近更新 更多