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

Mik*_*e T 9 python indexing numpy

我正在尝试使用来自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:])
Run Code Online (Sandbox Code Playgroud)

此时,两个3D阵列具有相同的形状,而minax0阵列具有形状(500,335).现在,我想使用第一维的索引位置将2D数组some2d中的值分配给3D数组.这是我正在尝试,但不起作用:othercubeminax0

othercube[minax0] = some2d    # or
othercube[minax0,:] = some2d
Run Code Online (Sandbox Code Playgroud)

抛出错误:

ValueError:在花式索引中尺寸太大

注意:我目前使用的是什么,但不是非常NumPythonic:

for r in range(shape3d[1]):
    for c in range(shape3d[2]):
        othercube[minax0[r, c], r, c] = some2d[r, c]
Run Code Online (Sandbox Code Playgroud)

我一直在网上挖掘找到可以索引的类似例子othercube,但我找不到任何优雅的东西.这需要高级索引吗?有小费吗?

Pau*_*aul 9

花哨的索引可能有点不直观.幸运的是,本教程有一些很好的例子.

基本上,您需要定义每个minidx适用的j和k .numpy并没有从形状中推断出它.

在你的例子中:

i = minax0
k,j = np.meshgrid(np.arange(335), np.arange(500))
othercube[i,j,k] = some2d
Run Code Online (Sandbox Code Playgroud)