numpy compute lags between leader and lagger timestamps

Viewed 46

I have 2 arrays of timestamps

leader = [1, 5, 15, 22]

lagger = [3, 4, 5, 6, 7, 8, 9, 10, 17]

I want to match every timestamp of the lagger with the one immediately preceding it in the leader and compute lags, obtaining the array

lags = [2, 3, 4, 1, 2, 3, 4, 5, 2]

Is there a quick manner to do with numpy/pandas?

3 Answers

I think searchsorted, given that lagger[0] > leader[0]:

leader = np.array([1, 5, 15, 22])
lagger = np.array([3, 4, 5, 6, 7, 8, 9, 10, 17])

lagger - leader[np.searchsorted(leader, lagger)-1] 

Output:

array([2, 3, 4, 1, 2, 3, 4, 5, 2])

Another way of doing it using masked arrays and subtractions:

np.ma.masked_less(np.subtract.outer(lagger,leader),1).min(1)
#[2 3 4 1 2 3 4 5 2]

This finds subtraction between all leader and lagger and masks non-positive ones and then finds the minimum for each lagger.

Try with numpy broadcast

[x[x>0].min() for x in lagger[:,None]-leader]
Out[107]: [2, 3, 4, 1, 2, 3, 4, 5, 2]
Related