创建一个时间序列,从现有值中选取值,但在python中更改日期

2024-05-05 09:06:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个时间序列,希望复制它并为其分配一组新的日期索引,因为我需要将其连接到原始序列(为了执行过滤,我需要更长的时间序列)

>>>len(ts_interp)
109
>>>ts_interp.head()
date
2016-12-06    0.118412
2016-12-13    0.741708
2016-12-20    0.729774
2016-12-27    0.717839
2017-01-03    0.705905
Freq: 7D, Name: 2, dtype: float64
>>>ts.interp.tail()
date
2018-12-04    0.022732
2018-12-11    0.022732
2018-12-18    0.022732
2018-12-25    0.022732
2019-01-01    0.022732
Freq: 7D, Name: 2, dtype: float64
>>>t1 = pd.to_datetime('2016-12-06') #first item
>>>t2 = pd.to_datetime('2019-01-01') #last item
>>>t2-t1
Timedelta('756 days 00:00:00')
# the last item of my new time series to be concatenated, 
# should be the nearest to:
>>>t1 - dt.timedelta(7)
Timestamp('2016-11-29 00:00:00')

我的时间序列必须考虑季节性,因此我想选择的值作为新时间序列的最后一个值应该最接近201x-11-29,即2018-11-27(年份必须为2016年)。我这样说:

>>>pre_values=ts_interp.loc['2016-12-06':'2018-11-27']
>>>pre_index = pd.date_range(start='2014-12-06', end='2016-11-27', freq='7D')
>>>pre_series=pd.Series(pre_values, index=pre_index)

但我的pre_系列只包含NaN

2014-12-06   NaN
2014-12-13   NaN
2014-12-20   NaN
2014-12-27   NaN
2015-01-03   NaN
...

如何创建一个时间序列,从现有时间序列中选取值,但更改日期?提前谢谢


Tags: tonamedateindex时间序列nanitem
1条回答
网友
1楼 · 发布于 2024-05-05 09:06:14

我不明白通过将时间序列串联两次进行“过滤”,您想要实现什么,但如果您坚持,请尝试以以下内容结束:

pre_series.loc[start_date1:end_date1] = \
    pre_series.loc[start_date2:end_date2].values

即将下半部分的值分配给上半部分

相关问题 更多 >