NumPy: Changing Shapes

Pujan Thapa
2 min readFeb 2, 2019

--

NumPy is a library which provides fast alternative to math operations in Python. There are several data types in NumPy like Scalar, Vector, Matrix and Tensors which represents the dimensions of data. Scalar represents empty tuple i.e., zero dimension, Vector is one-dimensional, Matrix is two-dimensional with rows and columns. Tensors are just like Vectors and Matrices but can have more than two dimensional data shape.

For example: You may have a vector, which is one dimensional but need a matrix which is two dimensional. You can follow two ways.

Let’s assume you have the following vector:

v = np.array([5,6,7,8])

If you print v.shape then you will get (4,). Here you are not getting another number because vectors are one dimensional and python doesn’t understand (4) as a tuple with one item. So there must be comma. So, the tuple includes the number and a comma.

But what if you want a 1x4 matrix? You can use reshape function, like so:

x = v.reshape(1,4)

Calling x.shape would return (1,4). If you wanted a 4x1 matrix, you could do this:

x = v.reshape(4,1)

The reshape function works for more than just adding a dimension of size 1.

numpy.reshape(a, newshape)

Gives a new shape to an array without changing its data.

Note : It is not always possible to change the shape of an array without copying the data. If you want an error to be raise if the data is copied, you should assign the new shape to the shape attribute of the array

Check out its documentation for more examples.

One more thing about reshaping NumPy arrays: if you see code from experienced NumPy users, special slicing syntax are used more instead of calling reshape. Using this syntax, the previous two examples would look like this:

x = v[None, :]

or

x = v[:, None]

Those lines create a slice that looks at all of the items of v but asks NumPy to add a new dimension of size 1 for the associated axis. It may look strange to you now, but it's a common technique so it's good to be aware of it.

--

--