切片3d numy数组返回奇怪的形状

2024-04-25 14:38:47 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我用一组坐标切片一个二维数组

>>> test = np.reshape(np.arange(40),(5,8))
>>> coords = np.array((1,3,4))
>>> slice = test[:, coords]

那么我的切片就有了我所期望的形状

^{pr2}$

但是如果我用一个3d数组重复这个

>>> test = np.reshape(np.arange(80),(2,5,8))
>>> slice = test[0, :, coords]

那么形状就是现在

>>> slice.shape
(3, 5)

这些不同有什么原因吗?分离指数会得到我所期望的形状

>>> slice = test[0][:][coords]
>>> slice.shape
(5, 3)

为什么这些视图会有不同的形状?在


Tags: test视图np切片slice原因数组coords
2条回答
slice = test[0, :, coords]

是一个简单的索引,实际上是说“取第一个坐标的第0个元素,第二个坐标的所有元素,以及第三个坐标的[1,3,4]”。或者更准确地说,取坐标(0,whatever,1)作为第一行,(0,whatever,2)将其作为第二行,(0,whatever,3)并将其作为第三行。有5个whatever,所以最后得到(3,5)。在

你举的第二个例子是这样的:

^{pr2}$

在本例中,您将看到一个(5,8)数组,然后获取第1、第3和第4个元素,即第1行、第3行和第4行,最后得到一个(5,3)数组。在

编辑讨论二维案例:

在二维情况下,其中:

>>> test = np.reshape(np.arange(40),(5,8))
>>> test
array([[ 0,  1,  2,  3,  4,  5,  6,  7],
       [ 8,  9, 10, 11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20, 21, 22, 23],
       [24, 25, 26, 27, 28, 29, 30, 31],
       [32, 33, 34, 35, 36, 37, 38, 39]])

行为类似。在

案例1:

>>> test[:,[1,3,4]]
array([[ 1,  3,  4],
       [ 9, 11, 12],
       [17, 19, 20],
       [25, 27, 28],
       [33, 35, 36]])

只需选择列1、3和4。在

案例2:

>>> test[:][[1,3,4]]
array([[ 8,  9, 10, 11, 12, 13, 14, 15],
       [24, 25, 26, 27, 28, 29, 30, 31],
       [32, 33, 34, 35, 36, 37, 38, 39]])

正在获取数组的第1、3和4个元素,它们是行。在

http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing

这些文档讨论了将高级索引和基本索引相结合的复杂性。在

test[0, :, coords]

索引coords首先出现,后面是{},生成{}。在

The easiest way to understand the situation may be to think in terms of the result shape. There are two parts to the indexing operation, the subspace defined by the basic indexing (excluding integers) and the subspace from the advanced indexing part. [in the case where]

The advanced indexes are separated by a slice, ellipsis or newaxis. For example x[arr1, :, arr2]. .... the dimensions resulting from the advanced indexing operation come first in the result array, and the subspace dimensions after that.

我记得在之前的一个SO问题中讨论过这种索引,但是需要一些挖掘才能找到它。在

https://stackoverflow.com/a/28353446/901925Why does the order of dimensions change with boolean indexing?

How does numpy order array slice indices?


test[0][:][coords]中的[:]不起任何作用。test[0][:,coords]生成所需的(5,3)结果。在

^{pr2}$

相关问题 更多 >