用2d数组索引3d numpy数组 [英] Indexing of 3d numpy arrays with 2d arrays

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

问题描述

我正在尝试从3d numpy数组中提取值.目前,我可以执行以下操作:

I am attempting to extract values from a 3d numpy array. At the moment I can perform the following operations:

newmesh.shape
(40,40,40)

newmesh[2,5,6]
6

但是,如果我尝试使用数组对它进行索引,结果将不符合预期;

However, if I try to index it with an array, the result is not as expected;

newmesh[np.array([2,5,6])].shape
(3, 42, 42)

我尝试使用np.take,但是会产生以下情况;

I have tried using np.take, however it produces the following;

np.take(newmesh,np.array([2,5,6]))
[-1 -1 -1]

有什么想法为什么会这样?我的目标是输入一个(n,3)数组,其中每一行对应一个newmesh值,即输入一个(n,3)数组将返回一个长度为n的一维数组.

Any ideas why this is happening? My goal is to input a (n,3) array, where each row corresponds to a value of newmesh, i.e. inputting a (n,3) array would give back a 1d array of length n.

推荐答案

使用idx作为(n,3)索引数组,使用linear-indexing的一种方法是使用

With idx as the (n,3) indexing array, one approach using linear-indexing would be with np.ravel_multi_index -

np.take(newmesh,np.ravel_multi_index(idx.T,newmesh.shape))

具有元组形成的方法看起来像这样-

An approach with tuple formation would look like this -

newmesh[tuple(idx.T)]

如果只有三个维度,您甚至可以使用柱状切片来索引每个维度,就像这样-

If there are just three dimensions, you can even just use columnar slices for indexing into each dimension, like so -

newmesh[idx[:,0],idx[:,1],idx[:,2]]

运行时测试:如果有兴趣查看与所列方法相关的性能数字,这是一个快速的运行时测试-

Runtime test If anyone's interested in seeing the performance numbers associated with the listed approaches, here's a quick runtime test -

In [18]: newmesh = np.random.rand(40,40,40)

In [19]: idx = np.random.randint(0,40,(1000,3))

In [20]: %timeit np.take(newmesh,np.ravel_multi_index(idx.T,newmesh.shape))
10000 loops, best of 3: 22.5 µs per loop

In [21]: %timeit newmesh[tuple(idx.T)]
10000 loops, best of 3: 20.9 µs per loop

In [22]: %timeit newmesh[idx[:,0],idx[:,1],idx[:,2]]
100000 loops, best of 3: 17.2 µs per loop

这篇关于用2d数组索引3d numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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