8

I have a random variable X sampled at random times T similar to this toy data:

import numpy as np
T = np.random.exponential(size=1000).cumsum()
X = np.random.normal(size=1000)

This timeseries looks like this: enter image description here

A key point is that the sampling interval is non-uniform: by this I mean that all elements of np.diff(T) are not equal. I need to resample the timeseries T,X on uniform intervals with a specified width dt, meaning (np.diff(T)==dt).all() should return True.

I can resample the timeseries on uniform intervals using scipy.interpolate.interp1d, but this method does not allow me to specify the interval size dt:

from scipy.interpolate import interp1d
T = np.linspace(T.min(),T.max(),T.size) # same range and size with a uniform interval
F = interp1d(T,X,fill_value='extrapolate') # resample the series on uniform interval
X = F(T) # Now it's resampled.

The essential issue is that interp1d does not accept an array T unless T.size==X.size.

Is there another method I can try to resample the time series T,X on uniform intervals of width dt?

2 Answers 2

8
dt = ...
from scipy.interpolate import interp1d   
Told = np.arange(T.min(),T.max(),T.size)
F = interp1d(Told,X,fill_value='extrapolate') 
Tnew = np.linspace(T.min(), T.max(), dt)
Xnew = F(Tnew)
3
  • 2
    oh, yeah, for sure. haha thank you! However I think linspace should be arange! Sep 18, 2019 at 20:32
  • I agree with @kevinkayaks. dt is meant to be delta time between resampled points, so np.arange() is the proper function. Nov 8, 2022 at 8:08
  • 1
    please add a few words on what the idea is in this solution.
    – LudvigH
    Mar 8 at 12:49
0

This was very useful for me. Please note, however, that line

F = interp1d(Told,X,fill_value='extrapolate') 

is not correct. It should read:'

F = interp1d(Told,X,kind='extrapolate')

or (in my case more useful):

F = interp1d(Told,X,kind='previous')
1
  • Thanks! I think the API may have actually changed in a recent scipy version. Just yesterday I realized some of my other interpolation scripts have quit working. Mar 8 at 11:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.