简体   繁体   English

当在numpy中删除维度时产生的数组形状

[英]resulting array shape when dropping dimension in numpy

Trying to understand how numpy selects elements when indexing in more than 2 dimensions. 试图了解numpy在两个以上维度建立索引时如何选择元素。

import numpy as np
x = np.arange(24).reshape(2,3,4)
x[:,:,0].shape #(2, 3)

In writing x[:,:,0] I am selecting all the elements along the "depth", all the "rows" and the first column. 在编写x[:,:,0]我将选择“深度”中的所有元素,所有“行”和第一列。 When thinking about this visually I would have thought numpy would return something with a shape of (2,3,1) but instead the last dimension is dropped. 在视觉上考虑这个问题时,我会以为numpy会返回形状为(2,3,1)的东西,但是最后一个维度被删除了。 This is reasonable but how does numpy populate the result? 这是合理的,但是numpy如何填充结果? Ie in this example, why does x[:,:,0] result in the elements [0,12] forming the first column. 即在此示例中,为什么x[:,:,0]导致元素[0,12]形成第一列。 Just trying to figure out the general logic which for some reason I am not comprehending at the moment. 只是想弄清楚由于某种原因我目前无法理解的一般逻辑。

General NumPy indexing is complicated, but this is still the easy case. 常规NumPy索引很复杂,但这仍然是简单的情况。 I've always felt that it helps to think in terms of how indexing the result corresponds to indexing the original array. 我一直认为,从索引结果到索引原始数组的方式思考问题会有所帮助。

The result of x[:, :, 0] is an array such that for any indices i and j , x[:, :, 0]是一个数组,对于任何索引ij

result[i, j] == x[i, j, 0]

Similarly, if you index a 5D array a as a[:, 1, :, 2, :] , the result is such that 同样,如果将5D数组a索引为a[:, 1, :, 2, :] ,则结果为

result[i, j, k] == a[i, 1, j, 2, k]

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

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