切片 numpy 数组时形状发生变化

Shape changing when slicing numpy arrayx

我以下面的数组为例:

lights = np.array([ [1,0,1], [0,1,1], [0,0,1], [1,1,1] ])

lights[0] returns 形状:(3,)

lights[0:1] returns 形状:(1, 3)

我不明白这种情况下numpy的逻辑是什么。 鉴于切片是独占的,[0:1] 类似于 [0]。 那么,为什么它会影响数组的形状?

lights 是形状为 (4,3).

的二维数组

lights[0] 的情况下,您需要该数组的第一个元素,它本身是一个大小为 3 的一维数组。因此你得到形状(3,)

现在 lights[0:1] 你做的不一样。你切出一个子数组。尽管这个子数组在一维中只包含一个元素,但它仍然是一个二维数组。

问问自己:如果你 lights[0:2] 会发生什么?您会期望形状为 (2,3) 的二维数组,对吗?因此,即使 lights[0:1] 返回的子数组可能与一维数组相同,NumPy 也不能只为您删除该维度。

如果您输入类似 lights[0:N] 的内容,其中 N 是一个变量,如果 N=1,NumPy 会自动删除 1 个维度,您每次都必须单独处理这种特殊情况。一个简单的例子,你想得到一个切片并设置它的第二个元素:

N = 2
t = lights[0:N]
t[0, 1] = 42

您可以将 N 设置为 1,它仍然有效。现在将其更改为 t = lights[0] 并且您的程序在下一行崩溃,因为您的数组只有一维。因此,如果 NumPy 会删除 lights[0:1] 的额外维度,您每次都必须为这种特殊情况编写额外的代码。

https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing-and-indexing

An integer, i, returns the same values as i:i+1 except the dimensionality of the returned object is reduced by 1. In particular, a selection tuple with the p-th element an integer (and all other entries :) returns the corresponding sub-array with dimension N - 1. If N = 1 then the returned object is an array scalar. These objects are explained in Scalars.

numpy 标量索引与切片索引与 Python 的列表索引一致:

In [119]: alist = [ [1,0,1], [0,1,1], [0,0,1], [1,1,1] ]                                               
In [120]: alist[0]                                                                                     
Out[120]: [1, 0, 1]     # one element of alist
In [121]: alist[0:1]                                                                                   
Out[121]: [[1, 0, 1]]    # a list with one element
In [122]: alist[0][1]    # nested selection of a number                                                     
Out[122]: 0

数组等价物,匹配使用[]:

In [123]: arr = np.array(alist)                                                                        
In [124]: arr                                                                                          
Out[124]: 
array([[1, 0, 1],
       [0, 1, 1],
       [0, 0, 1],
       [1, 1, 1]])
In [125]: arr[0]                                                                                       
Out[125]: array([1, 0, 1])
In [126]: arr[0:1]                                                                                     
Out[126]: array([[1, 0, 1]])
In [127]: arr[0,1]                                                                                     
Out[127]: 0

numpy 也可以使用元组、列表和数组进行索引。