I have two numpy arrays of unequal lengths:
a = numpy.array([108, 637, 1172, 1304, 2260, 2809])
b = numpy.array([109, 634, 2254, 2814])
I want to shorten a
such that the corresponding elements in each array are similar. The criteria for this correspondence is when the element of b
lies within the range: element a - 50 < element b < element a + 50
. Hence, the element with value 108
from a
is a match to the element with value 109
from b
. The resulting output should be:
a_prime = numpy.array([108, 637, 2260, 2809])
b_prime = numpy.array([109, 634, 2254, 2814])
I can achieve this using a double for
loop configuration:
a_prime = numpy.zeros(b.shape[0], dtype = int)
b_prime = numpy.copy(b)
for idx, element_b in enumerate(b):
for element_a in a:
if (element_a - 50) < element_b < (element_a + 50):
a_prime[idx] = element_a
However, for large array lengths this will be very time consuming. What would be the fast and more pythonic way to achieve the same result?