1

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?

6
  • Append (2,3) arrays along what axis? Use sample arrays to demonstrate what you have in mind? Commented Jun 17, 2016 at 12:25
  • Never mind about that just want to know why numpy.array([]).reshape(2,3) throws an error Commented Jun 17, 2016 at 12:26
  • numpy.array([]).reshape(2,3) throws error because numpy.array([]) has zero elements, so you can't reshape that to (2,3) that expects total 6 elements. Commented Jun 17, 2016 at 12:27
  • So why does numpy.array([]).reshape(0,4) work Commented Jun 17, 2016 at 12:28
  • 2
    Because .reshape(0,4) expects zero elements 0*4 = 0, while in (2,3), it expects 2*3 = 6 elems. Commented Jun 17, 2016 at 12:30

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.