0

I want to get the maximum and minimum value from a numpy array over multiple ranges. I found this solution for getting only the maximum over multiple ranges when the ranges are uniform. However, my ranges are not always uniform.

So if there is an array that has the numbers 1-9 and the ranges are the indices [0-2], [3-6], [7-8], I would like to get the max and min value from each range.

I have posted a possible solution below, but I wonder if numpy has a method to do this without a loop.

import numpy as np

a = np.array([1,2,3,4,5,6,7,8,9])
slices = [np.arange(0,3), np.arange(3,7), np.arange(7,9)]

max = np.empty(0)
min = np.empty(0)
for slice in slices:
    max = np.concatenate([max, np.max(a[slice])])
    min = np.concatenate([min, np.min(a[slice])])

min_and_max = np.concatenate([min,max])
4
  • 1
    Does your code work? I didn't realize np.ndarray objects had the concatenate method as an attribute (relevant). Also looks like a mismatch of dims? Commented Apr 28, 2023 at 22:44
  • Also, a series of concatenations with numpy arrays is significantly less efficient than using a python list, appending, then casting to a np.ndarray. Commented Apr 28, 2023 at 22:47
  • Use a straight forward list append or list comprehension. Don't try to be "pythonic" especially if you don't know what that means. Commented Apr 29, 2023 at 0:40
  • I fixed the concatenate and thanks for pointing out the inefficiencies of concatenating. These comments helped me clarify what I was really trying to ask: "Is a numpy method that could operate on the list of slices?" That way I could avoid using a loop and repeated concatenation and the inherent inefficiency of repeated concatenation. Commented Apr 30, 2023 at 17:00

1 Answer 1

2

ufunc.reduceat is precisely for this:

>>> a = np.array([1,2,3,4,5,6,7,8,9])
>>> slices = np.array([0, 3, 7])
>>> np.maximum.reduceat(a, slices)
array([3, 7, 9])
>>> np.minimum.reduceat(a, slices)
array([1, 4, 8])
>>> np.vstack([np.minimum.reduceat(a, slices),
...            np.maximum.reduceat(a, slices)])
array([[1, 4, 8],
       [3, 7, 9]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.