简体   繁体   English

多维数组中的多元素索引

[英]Multiple Element Indexing in multi-dimensional array

I have a 3d Numpy array and would like to take the mean over one axis considering certain elements from the other two dimensions. 我有一个3d Numpy数组,并且考虑来自其他两个维度的某些元素,我想在一个轴上取均值。

This is an example code depicting my problem: 这是一个描述我的问题的示例代码:

import numpy as np
myarray = np.random.random((5,10,30))
yy = [1,2,3,4]
xx = [20,21,22,23,24,25,26,27,28,29]
mymean = [ np.mean(myarray[t,yy,xx]) for t in np.arange(5) ]

However, this results in: 但是,这导致:

ValueError: shape mismatch: objects cannot be broadcast to a single shape

Why does an indexing like eg myarray[:,[1,2,3,4],[1,2,3,4]] work, but not my code above? 为什么索引像myarray [:,[1,2,3,4],[1,2,3,4]],但不是我上面的代码?

This is how you fancy-index over more than one dimension: 这就是你喜欢多个维度的索引:

>>> np.mean(myarray[np.arange(5)[:, None, None], np.array(yy)[:, None], xx],
            axis=(-1, -2))
array([ 0.49482768,  0.53013301,  0.4485054 ,  0.49516017,  0.47034123])

When you use fancy indexing, ie a list or array as an index, over more than one dimension, numpy broadcasts those arrays to a common shape, and uses them to index the array. 当你使用花式索引,即列表或数组作为索引,在多个维度上,numpy将这些数组广播到一个共同的形状,并使用它们索引数组。 You need to add those extra dimensions of length 1 at the end of the first indexing arrays, for the broadcast to work properly. 您需要在第一个索引数组的末尾添加长度为1的额外维度,以使广播正常工作。 Here are the rules of the game . 以下是游戏规则

Since you use consecutive elements you can use a slice: 由于您使用连续元素,您可以使用切片:

import numpy as np
myarray = np.random.random((5,10,30))
yy = slice(1,5)
xx = slice(20, 30)
mymean = [np.mean(myarray[t, yy, xx]) for t in np.arange(5)]

To answer your question about why it doesn't work: when you use lists/arrays as indices, Numpy uses a different set of indexing semantics than it does if you use slices. 回答你的问题为什么它不起作用:当你使用列表/数组作为索引时,Numpy使用一组不同的索引语义,而不是使用切片。 You can see the full story in the documentation and, as that page says, it "can be somewhat mind-boggling". 您可以在文档中看到完整的故事,正如该页面所说,它“可能有些令人难以置信”。

If you want to do it for nonconsecutive elements, you must grok that complex indexing mechanism. 如果您想为非连续元素执行此操作,则必须了解该复杂的索引机制。

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

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