I have the following dataframe, the date corresponds to quarterly periods and the amount (and other additional columns not shown here for simplification) corresponding to the associated id grouping. Dates are unique per id.
import pandas as pd
from numpy import nan
d = {'id': ['a', 'a', 'a', 'b', 'b'], 'date': ['2020-09-30', '2020-06-30', '2020-03-31',
'2020-09-30', '2020-06-30'], 'amount': [1, 2, nan , 5, nan]}
df = pd.DataFrame(data=d)
df['date'] = pd.to_datetime(df['date'])
df
id date amount
0 a 2020-09-30 1
1 a 2020-06-30 2
2 a 2020-03-31
3 b 2020-09-30 5
4 b 2020-06-30
I would like to extend the period of time that the quarters start by a set start quarter date in the past so that the quarter periods start and exist for the same dates for each id. In this example the data should start at 2019-12-31 and any quarters in between should be filled in if the row is missing.
I would like to backfill the missing values (such as amount) based on the most recent present value.
The output would look like this:
id date amount
a 2020-09-30 1
a 2020-06-30 2
a 2020-03-31 2
a 2019-12-31 2
b 2020-09-30 5
b 2020-06-30 5
b 2020-03-31 5
b 2019-12-31 5
What is the best way to go about this?