Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Data Science by (17.6k points)

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.

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...