30

How do I resample a time series in pandas to a weekly frequency where the weeks start on an arbitrary day? I see that there's an optional keyword base but it only works for intervals shorter than a day.

denfromufa
  • 5,610
  • 13
  • 81
  • 138
2daaa
  • 2,788
  • 7
  • 33
  • 44

4 Answers4

76

You can pass anchored offsets to resample, among other options they cover this case.

For example the weekly frequency from Monday:

ts.resample('W-MON')
Little Bobby Tables
  • 4,466
  • 4
  • 29
  • 46
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
5

You will be much safer with resampling based on days and then slicing every 7th day, e.g:

ts.resample('D').interpolate()[::7]

See the underlying problem with other approaches in this open pandas issue on github:

https://github.com/pandas-dev/pandas/issues/16381

denfromufa
  • 5,610
  • 13
  • 81
  • 138
4

Neither Andy Haydens nor denfromufas answer worked for me but that did:

df.resample('W', label='left', loffset=pd.DateOffset(days=1))

as described in that answer: https://stackoverflow.com/a/46712821/1743551

Sandro
  • 1,757
  • 1
  • 19
  • 29
0

You might want to double check your results. loffset seems to be for changing the labels on the sampled index, not the actual underlying time periods that are being employed in the resampling. If you read through the latest docs, the loffset parameter is deprecated, and they recommend modifying the index after the resampling, which again points to changing labels and not how the resulting values are calculated. The offset keyword seems to apply, but I'm not having a lot of luck with that.

https://pandas.pydata.org/pandas-docs/dev/reference/api/pandas.DataFrame.resample.html