numpy - 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]]]
我试图找出区别,但不能。
解决方案
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])
推荐阅读
- html5-canvas - 分组形状上的硬币旋转效果动画
- python - 无法使用 Scrapy 从父节点和子节点/标签获取文本
- python - 按特定顺序连接点
- kotlin - 如何使用 runBlocking 等待 CoroutineScope 的完成
- javascript - gridstack.js:添加的小部件现在可拖动
- php - 如何使用 PHP 将元素的键值推送到 array_push
- android - 如何将 3d 模型 (.obj) 导入 Android Studio?
- java - JavaFX:为什么 Window.xProperty() 和 Window.yProperty() 在有设置器时只读?
- javascript - 使用变量访问对象属性,如果不存在则回退到默认属性
- android - 不同厂家的区别