问题描述
我对 Numpy 中 x[:]
和 x[...]
之间的区别感到困惑。
例如,我有这个二维数组
[[4,1,9],[5,2,0]]
当我尝试打印出 x[:]
和 x[...]
时,它们都给了我相同的输出:
[[4,0]]
但是,当我尝试通过添加一维进行广播时
print(np.broadcast_to(x[:,None],(2,3,3)))
print(np.broadcast_to(x[...,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,[5,0]])
这些只是制作了一个完整的切片,原始的 view
:
In [93]: x[:]
Out[93]:
array([[4,0]])
In [94]: x[...]
Out[94]:
array([[4,0]])
In [95]: x[:,:]
Out[95]:
array([[4,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,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,1)
In [100]: x[:,None,:].shape # same as 97
Out[100]: (2,3)
In [101]: x[None].shape # same as [None,:] [None,...]
Out[101]: (1,3)
带有标量索引
In [102]: x[1,:] # same as x[1],x[1,...]
Out[102]: array([5,0])
In [103]: x[...,1] # same as x[:,1]
Out[103]: array([1,2])