NumPy:在3D切片中使用来自argmin的2D索引数组

10

我正在尝试使用argmin(或相关的argmax等函数)中的2D数组索引来索引大型3D数组。这是我的示例数据:

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:])

此时,两个3D数组具有相同的形状,而minax0数组的形状为(500,335)。现在我想使用minax0作为第一维度的索引位置,将2D数组some2d 的值赋给3D数组othercube。这是我尝试的代码,但不起作用:

othercube[minax0] = some2d    # or
othercube[minax0,:] = some2d

抛出错误:

ValueError:使用花式索引的维度过大

注意:我目前正在使用以下代码,但不太符合NumPy的规范:

for r in range(shape3d[1]):
    for c in range(shape3d[2]):
        othercube[minax0[r, c], r, c] = some2d[r, c]

我一直在网上搜寻类似的例子来索引othercube,但是我没有找到任何优雅的方法。这需要一个高级索引吗?有什么建议吗?


谢谢你遇到这个问题!因为它引发的答案,我的一天变得更好了。 - Richard
1个回答

10

花式索引可能有点不直观。幸运的是,这个教程有一些很好的例子。

基本上,你需要定义每个minidx适用的j和k。Numpy不能从形状中推断出来。

在你的示例中:

i = minax0
k,j = np.meshgrid(np.arange(335), np.arange(500))
othercube[i,j,k] = some2d

这个在一个4D数组中的3D索引数组上会怎么工作? - Elvin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接