Reputation: 677
I have an array of numbers each corresponding to an event and the times when the events occurred. For example,
ev=[0, 14, 23, 53, 3]
time=[0, 0.4, 0.75, 0.9, 1.1]
Imagine ev vs. time to be a (right-continuous) step function which changes values at the values in the time array. Now by resampling, I mean defining a new array of time values and looking up the values of ev function at these times. I want to resample the variable ev under an evenly spaced time array. For example, if t1 is an evenly spaced array, ev1 is the corresponding event list I need.
t1=[0, 0.2, 0.4, 0.6, 0.8, 1, 1.2]
ev1=[0, 0, 14, 14, 23, 53, 3]
Is it possible to do such a resampling of an event array in Python? Is there a direct command? Thanks.
Upvotes: 2
Views: 476
Reputation: 67507
You can use np.searchsorted
with side='right
to find the index of the last item in time
that is smaller than your new timings, and then use it to fetch values from the ev
array:
>>> np.take(ev, np.searchsorted(time, t1, side='right')-1)
array([ 0, 0, 14, 14, 23, 53, 3])
If you first convert ev
to a numpy array, fancy indecing may be more readable:
>>> ev = np.array(ev)
>>> idx = np.searchsorted(time, t1, side='right')-1
>>> ev[idx]
array([ 0, 0, 14, 14, 23, 53, 3])
Upvotes: 4
Reputation: 353569
I'm sure there's a slick sorting way to do this in pure numpy
, but here's a pandas
way anyhow.
>>> ev = [0, 14, 23, 53, 3]
>>> time = [0, 0.4, 0.75, 0.9, 1.1]
>>> ser = pd.Series(ev, index=time)
>>> ser
0.00 0
0.40 14
0.75 23
0.90 53
1.10 3
dtype: int64
>>> ser.reindex(np.arange(0, 1.4, 0.2), method='ffill')
0.0 0
0.2 0
0.4 14
0.6 14
0.8 23
1.0 53
1.2 3
dtype: int64
Upvotes: 2