Skip to content
Advertisement

Pandas method to back extend a time series by repeating the first value

Is there a method to extend a pandas time series into the past repeating the first value found in the serie?. For example:

serie = pd.Series(
    [1, 2, 3, 4, 5], index=pd.date_range("2022-01-01", "2022-01-05")
)

And I want an extended series

In [13]: extended_serie
Out[13]: 
2021-12-28    1
2021-12-29    1
2021-12-30    1
2021-12-31    1
2022-01-01    1
2022-01-02    2
2022-01-03    3
2022-01-04    4
2022-01-05    5
Freq: D, dtype: int64

I’m asking if exists a direct method.

Advertisement

Answer

Let’s try reindex and bfill or use fill_value argument of reindex as mozway kindly pointing out.

out = (serie.reindex(pd.date_range('2021-12-28', serie.index[0]).append(serie.index))
       .bfill())
# or
out = serie.reindex(pd.date_range('2021-12-28', serie.index[0]).append(serie.index), fill_value=serie.iloc[0])
print(out)

2021-12-28    1.0
2021-12-29    1.0
2021-12-30    1.0
2021-12-31    1.0
2022-01-01    1.0
2022-01-01    1.0
2022-01-02    2.0
2022-01-03    3.0
2022-01-04    4.0
2022-01-05    5.0
dtype: float64
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement