首页 > 解决方案 > Numpy 中 x[:] 和 x[...] 的区别

问题描述

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

例如,我有这个二维数组

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

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

[[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]]]

我试图找出区别,但不能。

标签: numpynumpy-ndarrayarray-broadcasting

解决方案


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]])

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

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])

推荐阅读