I'm trying to index large 3D arrays using a 2D array of indicies from argmin (or related argmax, etc. functions). Here is my example data:
import numpy as np
shape3d = (16, 500, 335)
shapelen = reduce(lambda x, y: x*y, shape3d)
# 3D array of [random] source integers
intcube = np.random.uniform(2, 50, shapelen).astype('i').reshape(shape3d)
# 2D array of indices of minimum value along first axis
minax0 = intcube.argmin(axis=0)
# Another 3D array where I'd like to use the indices from minax0
othercube = np.zeros(shape3d)
# A 2D array of [random] values I'd like to assign in othercube
some2d = np.empty(shape3d[1:])
At this point, both 3D arrays have the same shape, while the minax0
array has the shape (500, 335). Now I'd like assign values from the 2D array some2d
to the 3D array othercube
using minax0
for the index position of the first dimension. This is what I'm trying, but doesn't work:
othercube[minax0] = some2d # or
othercube[minax0,:] = some2d
throws the error:
ValueError: dimensions too large in fancy indexing
Note: What I'm currently using, but is not very NumPythonic:
for r in range(shape3d[1]):
for c in range(shape3d[2]):
othercube[minax0[r, c], r, c] = some2d[r, c]
I've been digging around the web to find similar examples that can index othercube
, but I'm not finding anything elegant. Would this require an advanced index? Any tips?
Slice Two-dimensional Numpy Arrays To slice elements from two-dimensional arrays, you need to specify both a row index and a column index as [row_index, column_index] . For example, you can use the index [1,2] to query the element at the second row, third column in precip_2002_2013 .
The numpy. argmin() method returns indices of the min element of the array in a particular axis. Return : Array of indices into the array with same shape as array.
With an axis specified, argmin takes one-dimensional subarrays along the given axis and returns the first index of each subarray's minimum value. It doesn't return all indices of a single minimum value. Save this answer.
ArgMin is typically used to find the smallest possible values given constraints. In different areas, this may be called the best strategy, best fit, best configuration and so on. If f and cons are linear or polynomial, ArgMin will always find a global minimum.
fancy indexing can be a little non-intuitive. Luckily the tutorial has some good examples.
Basically, you need to define the j and k where each minidx
applies. numpy doesn't deduce it from the shape.
in your example:
i = minax0
k,j = np.meshgrid(np.arange(335), np.arange(500))
othercube[i,j,k] = some2d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With