Numpy 中 x[:] 和 x[...] 的区别

Difference between x[:] and x[...] in Numpy

我对 Numpy 中 x[:]x[...] 之间的区别感到困惑。

例如,我有这个二维数组

[[4, 1, 9],
[5, 2, 0]]

当我试图打印出 x[:]x[...] 时,它们都给了我相同的输出:

[[4, 1, 9],
  [5, 2, 0]]

但是,当我尝试通过添加一维来广播它时

print(np.broadcast_to(x[:,None],(2,3,3)))
print(np.broadcast_to(x[...,None],(2,3,3)))

他们给了我不同的结果。

[[[4 1 9]
  [4 1 9]
  [4 1 9]]

 [[5 2 0]
  [5 2 0]
  [5 2 0]]]


[[[4 4 4]
  [1 1 1]
  [9 9 9]]

 [[5 5 5]
  [2 2 2]
  [0 0 0]]]

我想找出区别,但做不到。

In [91]: x = np.array([[4, 1, 9],
    ...: [5, 2, 0]])
In [92]: x
Out[92]: 
array([[4, 1, 9],
       [5, 2, 0]])

这些只是整片,view 原片:

In [93]: x[:]
Out[93]: 
array([[4, 1, 9],
       [5, 2, 0]])
In [94]: x[...]
Out[94]: 
array([[4, 1, 9],
       [5, 2, 0]])
In [95]: x[:,:]
Out[95]: 
array([[4, 1, 9],
       [5, 2, 0]])

尾随:根据需要添加,但您不能提供超过维数:

In [96]: x[:,:,:]
Traceback (most recent call last):
  File "<ipython-input-96-9d8949edcb06>", line 1, in <module>
    x[:,:,:]
IndexError: too many indices for array: array is 2-dimensional, but 3 were indexed

None 添加维度:

In [97]: x[:,None].shape       # after the first
Out[97]: (2, 1, 3)
In [98]: x[...,None].shape     # at the end
Out[98]: (2, 3, 1)
In [99]: x[:,:,None].shape     # after the 2nd
Out[99]: (2, 3, 1)
In [100]: x[:,None,:].shape    # same as 97
Out[100]: (2, 1, 3)
In [101]: x[None].shape        # same as [None,:,:] [None,...]
Out[101]: (1, 2, 3)

带有标量索引

In [102]: x[1,:]          # same as x[1], x[1,...]
Out[102]: array([5, 2, 0])
In [103]: x[...,1]        # same as x[:,1]
Out[103]: array([1, 2])