Skip to content Skip to sidebar Skip to footer

Numpy 4d Array Slicing

Why does slicing a 4d array give me a 3d array? I expected a 4d array with extent 1 in one of the dimensions. Example: print X.shape (1783, 1, 96, 96) Slice array: print X[11,:,:,

Solution 1:

Per the docs:

An integer, i, returns the same values as i:i+1 except the dimensionality of the returned object is reduced by 1. In particular, a selection tuple with the p-th element an integer (and all other entries :) returns the corresponding sub-array with dimension N - 1. If N = 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 is 1-dimensional, a[2] is 0-dimensional.

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

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

Similarly, X[11:12, :, :, :] has shape (1,1,96,96).


Post a Comment for "Numpy 4d Array Slicing"