【问题标题】:NumPy: use 2D index array from argmin in a 3D sliceNumPy:在 3D 切片中使用来自 argmin 的 2D 索引数组
【发布时间】:2011-10-09 22:28:38
【问题描述】:

我正在尝试使用来自 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)。现在我想将 2D 数组 some2d 中的值分配给 3D 数组 othercube,使用 minax0 作为第一维的索引位置。这是我正在尝试的,但不起作用:

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

抛出错误:

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

注意:我目前正在使用,但不是非常 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 吗?有什么建议吗?

【问题讨论】:

  • 感谢您遇到此问题!我的日子更适合它引发的答案。

标签: python indexing numpy


【解决方案1】:

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

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

在你的例子中:

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

【讨论】:

  • 这将如何在 4D 数组中的 3D 索引数组上工作?
猜你喜欢
  • 1970-01-01
  • 2022-10-04
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 2019-12-23
  • 2020-04-13
  • 1970-01-01
  • 2011-10-01
相关资源
最近更新 更多