NumPy: use 2D index array from argmin in a 3D slice

旧巷老猫 提交于 2019-12-22 04:09:11

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/6771551/numpy-use-2d-index-array-from-argmin-in-a-3d-slice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!