用列表切片数组

ken*_*eng 8 python arrays slice

所以,我创建了一个 numpy 数组:

a = np.arange(25).reshape(5,5)

数组([[ 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]])

传统切片a[1:3,1:3]返回

数组([[ 6, 7], [11, 12]])

就像在第二个中使用列表一样 a[1:3,[1,2]]

数组([[ 6, 7], [11, 12]])

然而,a[[1,2],[1,2]]返回

数组([ 6, 12])

显然我不明白这里的东西。也就是说,使用列表切片有时可能非常有用。

干杯,

ins*_*get 0

在最后一种情况下,两个单独的列表被视为单独的索引操作(这确实是一个尴尬的措辞,所以请耐心等待)。

Numpy 看到两个包含两个整数的列表,并认为您需要两个值。每个值的行索引来自第一个列表,而每个值的列索引来自第二个列表。因此,你得到a[1,1]a[2,2]。该:符号不仅扩展到您准确推导的列表,而且还告诉 numpy 您想要该范围内的所有行/列。

如果您提供手动管理的列表索引,它们必须具有相同的大小,因为每个/任何列表的大小就是您将返回的元素数量。例如,如果您想要第 1、2、3 行的第 1 列和第 2 列中的元素:

>>> a[1:4,[1,2]]
array([[ 6,  7],
       [11, 12],
       [16, 17]])
Run Code Online (Sandbox Code Playgroud)

>>> a[[1,2,3],[1,2]]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (2,)
Run Code Online (Sandbox Code Playgroud)

(1,1)前者告诉 numpy 你想要一定范围的行和特定列,而后者则说“给我、(2,2)和处的元素(3, hey! what the?! where's the other index?)