简体   繁体   English

用numpy进行多维索引的最佳方法是什么?

[英]What is the best way to do multi-dimensional indexing with numpy?

I am trying to do some indexing on a 3D numpy array. 我正在尝试对3D numpy数组进行索引。 Basically I have an array phi which has shape (F,A,D) ; 基本上我有一个形状为(F,A,D)的数组phi ; for example (5, 3, 7) . 例如(5, 3, 7) Generated, for example as follows: 生成的示例如下:

F=5; A=3; D=7; phi = np.random.random((F,A,D))

My goal is to be able to index over A and D , with a 2D array such as [[0,1,2],[5,5,6]] , which means take the values indexed by 0 in the 3rd dimension, for the the first position in A , the values indexed by 1 in the 3rd dimension for the second position of A and so on. 我的目标是使用2 [[0,1,2],[5,5,6]]类的2D数组在AD上建立索引,这意味着在第3维上采用以0索引的值,在第一位置A ,这些值由1对的第二位置的第三尺寸索引A等和。 The result should have a shape that is (F,A,2) or (F,2,A) . 结果应具有(F,A,2)(F,2,A)的形状。

This would be equivalent to manually cycling all the values of the "indexer array" such as: 这等同于手动循环“索引器数组”的所有值,例如:

phi[:,0,0]; phi[:,1,1]; phi[:,2,2]
phi[:,0,5]; phi[:,1,5]; phi[:,2,6]

Intuitively I would do something like phi[:,:,[[0,1,2],[3,3,3]]] , but it's shape ends up being (5, 3, 2, 3) . 直观地讲,我会做类似phi[:,:,[[0,1,2],[3,3,3]]]事情,但是它的形状最终是(5, 3, 2, 3)

Any ideas on how to obtain the correct result? 关于如何获得正确结果的任何想法?

I think this is what you want 我想这就是你想要的

phi[:,range(A),[[0,1,2],[5,5,6]]]

Your attempt 你的尝试

phi[:,:,[[0,1,2],[5,5,6]]]

takes the values along the third dimension for every values of the first two dimensions, therefore you end up with a shape of (5,3,2,3) . 对于前两个维的每个值,沿第三个维取值,因此最终得到的形状为(5,3,2,3)

However, according to your example you want a continous increase in the second dimension which is accomplished in my code by range(A) and numpy's broadcasting. 但是,根据您的示例,您希望第二维不断增加,这在我的代码中是通过range(A)和numpy的广播来实现的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM