Sruli
Sruli

Reputation: 365

Reshaping Numpy Arrays to a multidimensional array

For a numpy array I have found that

x = numpy.array([]).reshape(0,4)

is fine and allows me to append (0,4) arrays to x without the array losing its structure (ie it dosnt just become a list of numbers). However, when I try

x = numpy.array([]).reshape(2,3)

it throws an error. Why is this?

Upvotes: 1

Views: 874

Answers (2)

SvbZ3r0
SvbZ3r0

Reputation: 638

reshape is not an 'append' function. It reshapes the array you give it to the dimensions you want.

np.array([]).reshape(0,4) works because you reshape a zero element array to a 0x4(=0 elements) array.
np.reshape([]).reshape(2,3) doesn't work because you're trying to reshape a zero element array to a 2x3(=6 elements) array.

To create an empty array use np.zeros((2,3)) instead.

And in case you're wondering, numpy arrays can't be appended to. You'll have to work around by casting it as a list, appending what you want and the converting back to a numpy array. Preferably, you only create a numpy array when you don't mean to append data later.

Upvotes: 0

hashcode55
hashcode55

Reputation: 5860

This out put will explain what it mean to reshape an array...

np.array([2, 3, 4, 5, 6, 7]).reshape(2, 3)

Output -

array([[2, 3, 4],
       [5, 6, 7]])

So reshaping just means reshaping an array. reshape(0, 4) means convert the current array into a format with 0 rows and 4 columns intuitively. But 0 rows means no elements means so it works as your array is empty. Similarly (2, 3) means 2 rows and 3 columns which is 6 elements...

Upvotes: 1

Related Questions