gpt4 book ai didi

python - 用一个月而不是一年创建 Pandas 时间序列

转载 作者:太空狗 更新时间:2023-10-30 01:34:37 27 4
gpt4 key购买 nike

使用 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 对象似乎不支持这一点(它会抛出错误)。有没有比创建带有年份的时间序列,然后在用于索引时间序列之前修改日期时间对象更好的方法?

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

最佳答案

尝试 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

关于python - 用一个月而不是一年创建 Pandas 时间序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16800824/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com