Pandas .resample() or .asfreq() fill forward times

I'm trying to resample a dataframe with a time series from 1-hour increments to 15-minute. Both .resample() and .asfreq() do almost exactly what I want, but I'm having a hard time filling the last three intervals.

I could add an extra hour at the end, resample, and then drop that last hour, but it feels hacky.

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

Desired 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

Thoughts?

1 answer

  • answered 2018-03-20 14:41 cᴏʟᴅsᴘᴇᴇᴅ

    Not sure about asfreq but reindex works wonderfully:

    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