# Minimum distance for each value in array respect to other

0 votes
1 view

I have two numpy arrays of integers A and B. The values in array A and B correspond to time-points at which events A and B occurred. I would like to transform A to contain the time since the most recent event b occurred.

I know I need to subtract each element of A by its nearest smaller the element of B but am unsure of how to do so. Any help would be greatly appreciated.

>>> import numpy as np

>>> A = np.array([11, 12, 13, 17, 20, 22, 33, 34])

>>> B = np.array([5, 10, 15, 20, 25, 30])

Desired Result:

cond_a = relative_timestamp(to_transform=A, reference=B)

cond_a

>>> array([1, 2, 3, 2, 0, 2, 3, 4])

## 1 Answer

0 votes
by (41.4k points)

You would like to transform A to contain the time since the most recent event b occurred.For this, you have to find the closest element in B for each element in A.

So,you can use np.searchsorted to find the indices where the elements of A should be inserted in B to maintain order.

idx = np.searchsorted(B, A, side='right')

result = A-B[idx-1]

If you want to learn data science in-depth then enroll for best data science training.

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer