kosmos
kosmos

Reputation: 367

In numpy array how is dimension changed when slicing? Explain the following code

In the following code, the transpose works.

b = numpy.arange(4,3)
print(b[1:3,-1:)
print(b[1:3,-1:].shape)
print(b[1:3,-1:].T)
print(b[1:3,-1:].T.shape)

In the following case, transpose does not.

b = numpy.arange(4,3)
print(b[1:3,-1)
print(b[1:3,-1].shape)
print(b[1:3,-1].T)
print(b[1:3,-1].T.shape)

Upvotes: 0

Views: 125

Answers (1)

lxop
lxop

Reputation: 8595

Slicing a numpy array behaves differently depending on whether you slice with a range or a scalar. Your first example slices with a range, so although it ends up with the second dimension only having size 1, that dimension remains. Your second example slices with a scalar, and in that case the appropriate dimension is collapsed. So in the second example, you are left with a one-dimensional array, which doesn't do anything under transpose - it doesn't have any other dimensions to swap around.

Upvotes: 2

Related Questions