tsorn
tsorn

Reputation: 3625

Numpy reshape sub-list

For some reason, numpy reports the shape of 1-dimensional numpy-arrays without the number of rows. A numpy array with 784 elements has the shape: (784,). This is a problem, because the library I use expect a correct shape property (e.g. (784, 1)).

If I just have a single array, I can do this: train_y = train_y.reshape((train_y.shape[0], 1) But is there a way to reshape sub-arrays without doing a for-loop? I have an array with shape
(60000, 784), however, the sub-arrays have the shape (784,)and I would like them to be (784,1) instead.

Upvotes: 0

Views: 1148

Answers (1)

user2357112
user2357112

Reputation: 280837

NumPy is an n-dimensional array library, not a matrix library. 1D arrays don't have rows.

If you want a view of an arbitrary array with an extra length-1 axis stuck on the end, you can do that:

train_y = train_y[..., np.newaxis]
# or
train_y = train_y.reshape(train_y.shape + (1,))

though it may be better to change how you're initially creating this train_y array.

This will generate an array with shape (60000, 784, 1). Depending on your expectations, this might be exactly what you want, or you might consider it an abomination. In any case, train_y[0] will have shape (784, 1).

Upvotes: 2

Related Questions