-1

I am trying to get the argmax from one ndaray and use it to get values from another ndarray, but I am doing something wrong.

ndvi_array = np.random.randint(0, 255, size=(4, 1, 100, 100))
image_array = np.random.randint(0, 255, size=(4, 12, 100, 100))
ndvi_argmax = ndvi_array.argmax(0)
print(f"NDVI argmax shape: {ndvi_argmax.shape}")
zipped = tuple(zip(range(len(ndvi_argmax)), ndvi_argmax))
result = image_array[zipped]
print(f"Result share: {result.shape}")

I get the following error:

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

How can I get an array of shape (1,12,100,100) with the maximum values?

Vitaly Olegovitch
  • 3,509
  • 6
  • 33
  • 49

1 Answers1

1
>>> result = np.take_along_axis(
...     image_array,
...     ndvi_array.argmax(axis=0, keepdims=True),
...     axis=0,
    )

>>> print(f"{result.shape = }")
result.shape = (1, 12, 100, 100)
paime
  • 2,901
  • 1
  • 6
  • 17
  • 1
    Checking the [doc for `argmax`](https://numpy.org/doc/stable/reference/generated/numpy.argmax.html) it says `keepdims` kwarg is "New in version 1.22.0.". Either update numpy version or replace with `ndvi_array.argmax(...)[None, ...]` to insert a new axis where you lost it by reduction. – paime Jun 28 '22 at 16:12