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

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

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

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

抛出错误:

ValueError: dimensions too large in fancy indexing

注意:我目前使用的不是 NumPythonic:

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

我一直在网络上寻找可以索引 othercube 的类似示例,但我没有找到任何优雅的东西。这需要 advanced index 吗? ?有什么建议吗?

最佳答案

花哨的索引可能有点不直观。幸运的是 tutorial有一些很好的例子。

基本上,您需要定义每个 minidx 适用的 j 和 k。 numpy 不会从形状中推导出它。

在你的例子中:

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

关于python - NumPy:在 3D 切片中使用 argmin 中的 2D 索引数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6771551/

相关文章:

arrays - 如何在 PostgreSQL 中获取数组的最后一个元素?

mysql - 在不知道其名称的情况下删除 MySQL 列索引

mysql 7列pk与1列md5唯一约束

python - 在 cython 中声明 numpy 数组和 c 指针

python - 将辅助 y 轴刻度与主 x 轴上的带状图对齐

python - 将 Flask 表单值转换为 int

Python 进程在 Numpy 数组中仅使用 1.6 GB RAM Ubuntu 32 位

python - Python 中 range() 中的嵌套 range()

python - 如何将一串十六进制值转换为整数列表?

python - 使用 pandas DataFrame 获取第 10 个最常见值的计数