Numpy 4D数组切片 [英] Numpy 4d array slicing
问题描述
为什么切片4d数组会给我3d数组?我期望其中一个维度的范围为1的4d数组.
Why does slicing a 4d array give me a 3d array? I expected a 4d array with extent 1 in one of the dimensions.
示例:
print X.shape
(1783, 1, 96, 96)
切片数组:
print X[11,:,:,:].shape
或
print X[11,:].shape
给了我(1, 96, 96)
,但是我期望(1, 1, 96, 96)
我可以通过print X[11:12,:].shape
做到这一点,但是我想知道为什么第一种方法不能按我预期的那样工作?
I can do it by print X[11:12,:].shape
, but I wonder why the first method doesn't work as I expect?
推荐答案
每文档:
整数
i
返回与i:i+1
相同的值,除了返回的对象的维数减小了1
.特别是,第p
个元素为整数(以及所有其他条目:
)的选择元组将返回尺寸为N - 1
的相应子数组.如果为N = 1
,则返回的对象为数组标量.
An integer,
i
, returns the same values asi:i+1
except the dimensionality of the returned object is reduced by1
. In particular, a selection tuple with thep
-th element an integer (and all other entries:
) returns the corresponding sub-array with dimensionN - 1
. IfN = 1
then the returned object is an array scalar.
因此,当索引为整数时,将返回该索引处的值并删除相应的轴.在一个维度上,行为符合您的预期:
Thus, when your index is an integer, the value(s) at that index is(are) returned and the corresponding axis is removed. In one dimension the behavior is as you would expect:
In [6]: a = np.arange(5); a
Out[6]: array([0, 1, 2, 3, 4])
In [7]: a[2]
Out[7]: 2
In [8]: a[2].shape
Out[8]: ()
a
是1维的,a[2]
是0维的.
a
is 1-dimensional, a[2]
is 0-dimensional.
在较大的尺寸中,如果X
是4维且形状为(1783,1,96,96)
,则
X[11,:,:,:]
返回所有值,其中第一个轴索引等于11,然后删除该轴.所以X[11,:,:,:].shape
是(1,96,96)
.
In higher dimensions, if X
is 4-dimensional and of shape (1783,1,96,96)
, then
X[11,:,:,:]
returns all the values where the first axis index equals 11 and then that axis is removed. So X[11,:,:,:].shape
is (1,96,96)
.
当切片指定一个范围(例如a[2:3]
)时,将返回该范围内的所有值,并且不删除轴:
When the slice specifies a range, such as a[2:3]
then all the values within that range are returned and the axis is not removed:
In [9]: a[2:3]
Out[9]: array([2])
In [10]: a[2:3].shape
Out[10]: (1,)
类似地,X[11:12, :, :, :]
的形状为(1,1,96,96)
.
这篇关于Numpy 4D数组切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!