: 和 , 在 numpy 中的区别 [英] Difference between : and , in numpy
问题描述
一些资源提到在numpy
的数组切片中,array[2,:,1]
的结果与array[2][:][1]
,但在这种情况下我没有得到相同的:
Some resources have mentioned that in numpy
's array slicing, array[2,:,1]
results in the same as array[2][:][1]
, but I do not get the same ones in this case:
array3d = np.array([[[1, 2], [3, 4]],[[5, 6], [7, 8]], [[9, 10], [11, 12]]])
array3d[2,:,1]
out: array([10, 12])
和:
array3d[2][:][1]
out: array([11, 12])
有什么区别?
推荐答案
一些资源是错误的!
In [1]: array3d = np.array([[[1, 2], [3, 4]],[[5, 6], [7, 8]], [[9, 10], [11, 12
...: ]]])
In [2]: array3d
Out[2]:
array([[[ 1, 2],
[ 3, 4]],
[[ 5, 6],
[ 7, 8]],
[[ 9, 10],
[11, 12]]])
当索引都是标量时,这种分解有效:
When the indices are all scalar this kind of decomposition works:
In [3]: array3d[2,0,1]
Out[3]: 10
In [4]: array3d[2][0][1]
Out[4]: 10
一个索引减少了维度,选择了一个平面":
One index reduces the dimension, picking one 'plane':
In [5]: array3d[2]
Out[5]:
array([[ 9, 10],
[11, 12]])
[:]
上什么都不做 - 它本身不是占位符.在多维索引中,它是一个切片——该维度中的整个事物.我们在列表中看到了相同的行为.alist[2]
返回一个元素,alist[:]
返回整个列表的副本.
[:]
on that does nothing - it is not a place holder by itself. Within the multidimensional index it is a slice - the whole thing in that dimension. We see the same behavior with lists. alist[2]
returns an element, alist[:]
returns a copy of the whole list.
In [6]: array3d[2][:]
Out[6]:
array([[ 9, 10],
[11, 12]])
记住,numpy
是一个 python 包.Python 语法仍然适用于所有级别.x[a][b][c]
按顺序进行 3 次索引操作,链接"它们.x[a,b,c]
是一种索引操作,将 的元组传递给 x
.这是解释该元组的 numpy 代码.
Remember, numpy
is a python package. Python syntax still applies at all levels. x[a][b][c]
does 3 indexing operations in sequence, 'chaining' them. x[a,b,c]
is one indexing operation, passing a tuple of to x
. It's numpy code that interprets that tuple.
我们必须在剩余维度上使用多维索引:
We have to use a multidimensional index on the remaining dimensions:
In [7]: array3d[2][:,1]
Out[7]: array([10, 12])
In [8]: array3d[2,:,1]
Out[8]: array([10, 12])
解释器实际上做了:
In [9]: array3d.__getitem__((2,slice(None),1))
Out[9]: array([10, 12])
In [11]: array3d.__getitem__(2).__getitem__((slice(None),1))
Out[11]: array([10, 12])
这篇关于: 和 , 在 numpy 中的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!