Is there a method to extend a pandas time series into the past repeating the first value found in the serie?. For example:
JavaScript
x
4
1
serie = pd.Series(
2
[1, 2, 3, 4, 5], index=pd.date_range("2022-01-01", "2022-01-05")
3
)
4
And I want an extended series
JavaScript
1
13
13
1
In [13]: extended_serie
2
Out[13]:
3
2021-12-28 1
4
2021-12-29 1
5
2021-12-30 1
6
2021-12-31 1
7
2022-01-01 1
8
2022-01-02 2
9
2022-01-03 3
10
2022-01-04 4
11
2022-01-05 5
12
Freq: D, dtype: int64
13
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.
JavaScript
1
5
1
out = (serie.reindex(pd.date_range('2021-12-28', serie.index[0]).append(serie.index))
2
.bfill())
3
# or
4
out = serie.reindex(pd.date_range('2021-12-28', serie.index[0]).append(serie.index), fill_value=serie.iloc[0])
5
JavaScript
1
14
14
1
print(out)
2
3
2021-12-28 1.0
4
2021-12-29 1.0
5
2021-12-30 1.0
6
2021-12-31 1.0
7
2022-01-01 1.0
8
2022-01-01 1.0
9
2022-01-02 2.0
10
2022-01-03 3.0
11
2022-01-04 4.0
12
2022-01-05 5.0
13
dtype: float64
14