Python – Pandas .resample() or .asfreq() padding time forward

Pandas .resample() or .asfreq() padding time forward… here is a solution to the problem.

Pandas .resample() or .asfreq() padding time forward

I’m trying to resample a dataframe using a time series from 1-hour increments to 15 minutes. .resample() and .asfreq() worked almost exactly for me, but I had a hard time filling the last three intervals.

I could add an hour at the end, resample, and then remove the last hour, but that feels bad.

Current code:

df = pd. DataFrame({'date':pd.date_range('2018-01-01 00:00', '2018-01-01 01:00', freq = '1H'), 'num':5})
df = df.set_index('date').asfreq('15T', method = 'ffill', how = 'end').reset_index()

Current output:

                 date  num
0 2018-01-01 00:00:00    5
1 2018-01-01 00:15:00    5
2 2018-01-01 00:30:00    5
3 2018-01-01 00:45:00    5
4 2018-01-01 01:00:00    5

Expected output:

                 date  num
0 2018-01-01 00:00:00    5
1 2018-01-01 00:15:00    5
2 2018-01-01 00:30:00    5
3 2018-01-01 00:45:00    5
4 2018-01-01 01:00:00    5
5 2018-01-01 01:15:00    5
6 2018-01-01 01:30:00    5
7 2018-01-01 01:45:00    5

Idea?

Solution

Not sure about asfreq but reindex works just fine :

df.set_index('date').reindex(
      pd.date_range(
          df.date.min(), 
          df.date.max() + pd. Timedelta('1H'), freq='15T', closed='left'
      ), 
      method='ffill'
)

num
2018-01-01 00:00:00    5
2018-01-01 00:15:00    5
2018-01-01 00:30:00    5
2018-01-01 00:45:00    5
2018-01-01 01:00:00    5
2018-01-01 01:15:00    5
2018-01-01 01:30:00    5
2018-01-01 01:45:00    5

Related Problems and Solutions