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

10 投票
1 回答
3044 浏览
提问于 2025-04-16 21:58

我正在尝试用一个二维数组的索引来给大型三维数组进行索引,这个二维数组是通过一些函数(比如argmin或相关的argmax等)得到的。下面是我的示例数据:

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

此时,这两个三维数组的形状是一样的,而minax0数组的形状是(500, 335)。现在我想用二维数组some2d中的值来给三维数组othercube赋值,使用minax0作为第一维的索引位置。我尝试了这样做,但没有成功:

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

结果出现了错误:

ValueError: fancy indexing中的维度太大

注意:我现在使用的方法虽然可以,但不是很符合NumPy的风格:

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

我在网上查找类似的例子,希望能找到可以给othercube索引的方法,但没有找到什么优雅的解决方案。这是否需要一个高级索引?有什么建议吗?

1 个回答

10

花式索引可能有点让人摸不着头脑。不过幸运的是,这里有个教程,里面有一些不错的例子。

简单来说,你需要定义每个minidx适用的j和k。numpy不会根据形状自动推断这些值。

在你的例子中:

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

撰写回答