在pandas中直接向后扩展数据时间索引

时间:2018-02-22 11:18:53

标签: python pandas

假设我有一个datetimeindex。 (在这个例子中,我手动设置日期范围,但实际上,有很多日期索引,我不能手动指定开始日期。)

date_idx = pd.DatetimeIndex(pd.date_range("2000-1-1",periods=3))  
DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03'], dtype='datetime64[ns]', freq='D')

我想将索引扩展到3天,如下所示。

DatetimeIndex(['1999-12-29', '1999-12-30', '1999-12-31', '2000-01-01',
               '2000-01-02', '2000-01-03'],
              dtype='datetime64[ns]', freq=None)

我绕道而行,得到了我想要的东西。有没有更简单的方法呢?

later = date_idx.tolist()
begin_day = later[0]
former = pd.date_range(begin_day, periods=3 ).shift(-3).tolist()
result = pd.DatetimeIndex(former + later)

1 个答案:

答案 0 :(得分:2)

shift需要union

N = 3
print (date_idx.shift(-N).union(date_idx[N-1:]))
DatetimeIndex(['1999-12-29', '1999-12-30', '1999-12-31', '2000-01-01',
               '2000-01-02', '2000-01-03'],
              dtype='datetime64[ns]', freq='D')

使用其他DatetimeIndex测试:

date_idx = pd.DatetimeIndex(pd.date_range("2000-1-1",periods=10))  
print (date_idx)
DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04',
               '2000-01-05', '2000-01-06', '2000-01-07', '2000-01-08',
               '2000-01-09', '2000-01-10'],
              dtype='datetime64[ns]', freq='D')

later = date_idx.tolist()
begin_day = later[0]
former = pd.date_range(begin_day, periods=5 ).shift(-5).tolist()
r = pd.DatetimeIndex(former + later)
print (r)
DatetimeIndex(['1999-12-27', '1999-12-28', '1999-12-29', '1999-12-30',
               '1999-12-31', '2000-01-01', '2000-01-02', '2000-01-03',
               '2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07',
               '2000-01-08', '2000-01-09', '2000-01-10'],
              dtype='datetime64[ns]', freq=None)

N = 5
print (date_idx.shift(-N).union(date_idx[N-1:]))
DatetimeIndex(['1999-12-27', '1999-12-28', '1999-12-29', '1999-12-30',
               '1999-12-31', '2000-01-01', '2000-01-02', '2000-01-03',
               '2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07',
               '2000-01-08', '2000-01-09', '2000-01-10'],
              dtype='datetime64[ns]', freq='D')