Suppose I have a NumPy array of integers.
arr = np.random.randint(0, 1000, 1000)
And I have two arrays lower
and upper
, which represent the lower and upper bounds respectively on slices arr
. These intervals are overlapping and variable, however lowers
, and uppers
are guaranteed as a nondecreasing.
lowers = np.array([0, 5, 132, 358, 566, 822])
uppers = np.array([45, 93, 189, 533, 800, 923])
I want to find the min and max of each fragment arr
defined by lowers
and uppers
, and store them in another array.
out_arr = np.empty((lowers.size, 2))
What is the most efficient way to do this ? I am worried that there is no vectorized approach since I do not see how I wrap indexing in a loop.
My current approach is just
for i in range(lowers.size):
arr_v = arr[lowers[i]:uppers[i]]
out_arr[i,0] = np.amin(arr_v)
out_arr[i,1] = np.amax(arr_v)
which leaves me with the desired result, for example,
In [304]: out_arr
Out[304]:
array([[ 26., 908.],
[ 18., 993.],
[ 0., 968.],
[ 3., 999.],
[ 1., 998.],
[ 0., 994.]])
.