Se7eN
Se7eN

Reputation: 608

slicing 2d numpy array

I have a numpy array padded_train_x of shape (2500,500).

The problem is, when I try to get the shape of an element of this array like padded_train_x[0].shape it outputs (500,) but when I run it as padded_train_x[0:1] it outputs (1,500). Why does this happen?

I'm trying to make prediction in an LSTM model using keras but I have to use padded_train_x[0:1] as the input instead of simply padded_train_x[0]

Upvotes: 1

Views: 560

Answers (2)

filippo
filippo

Reputation: 5294

As to why it happens, let's wait for someone more expert, not sure there really is a reason.

NumPy keeps dimensions when slicing and drops them when indexing. It's actually a Python thing, the same happens with lists.

You can drop single-dimensional axes with np.squeeze

a = np.ones((2500, 500))

a[0].shape
(500,)

a[0:1].shape
(1, 500)

a[0:1].squeeze().shape
(500,)

Upvotes: 2

Ilya
Ilya

Reputation: 193

That is because making slice by padded_train_x[0:1] you get 2d array:

a = np.linspace(1024).reshape(64,-1)
b = a[0]
c = a[0:1]

b
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])
b[0]
0

c
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15]])
c[0]
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])

Upvotes: 2

Related Questions