NumPy:在3D切片中使用argmin的2D索引数组 [英] NumPy: use 2D index array from argmin in a 3D slice

查看:99
本文介绍了NumPy:在3D切片中使用argmin的2D索引数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to index large 3D arrays using a 2D array of indicies from argmin (or related argmax, etc. functions). Here is my example data:

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 表示第一维的索引位置。这是我正在尝试但不起作用:

At this point, both 3D arrays have the same shape, while the minax0 array has the shape (500, 335). Now I'd like assign values from the 2D array some2d to the 3D array othercube using minax0 for the index position of the first dimension. This is what I'm trying, but doesn't work:

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

抛出错误:


ValueError:花式索引中的维度太大

ValueError: dimensions too large in fancy indexing

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

Note: What I'm currently using, but is not very NumPythonic:

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

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

I've been digging around the web to find similar examples that can index othercube, but I'm not finding anything elegant. Would this require an advanced index? Any tips?

推荐答案

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

fancy indexing can be a little non-intuitive. Luckily the tutorial has some good examples.

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

Basically, you need to define the j and k where each minidx applies. numpy doesn't deduce it from the shape.

在你的例子中:

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

这篇关于NumPy:在3D切片中使用argmin的2D索引数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆