Skip to content Skip to sidebar Skip to footer

Efficient Way To Get All Numpy Slices For Different Ranges

I want to slice the same numpy array (data_arra) multiple times to find each time the values in a different range data_ar shpe: (203,) range_ar shape: (1000,) I implemented it with

Solution 1:

You can use numba to speed up the computations.

import numpy as np
import numba
from numba.typed importListimport timeit

data_ar = np.array([1,3,4,6,10,12])
range_ar = np.array([7,4,2])
delta = 3deffoo(data_ar, range_ar):
    results_ar = list()
    for i in range_ar:
        results_ar.append(data_ar[( (data_ar>=(i-delta)) & (data_ar<(i+delta)) )])

print(timeit.timeit(lambda :foo(data_ar, range_ar)))

@numba.njit(parallel=True, fastmath=True)deffoo(data_ar, range_ar):
    results_ar = List()
    for i in range_ar:
        results_ar.append(data_ar[( (data_ar>=(i-delta)) & (data_ar<(i+delta)) )])

print(timeit.timeit(lambda :foo(data_ar, range_ar)))

15.53519330600102

1.6557575029946747

An almost 9.8 times speedup.

Solution 2:

You could use np.searchsorted like this:

data_ar = np.array([1, 3, 4, 6, 10, 12])
range_ar = np.array([7, 4, 2])
delta = 3bounds = range_ar[:, None] + delta * np.array([-1, 1])

result = [data_ar[slice(*row)] for row in np.searchsorted(data_ar, bounds)]

Post a Comment for "Efficient Way To Get All Numpy Slices For Different Ranges"