NumPy library is a package which enriches Python with many interesting helping functions. We know that array is not present in Python by default. So it's sometimes complicated to do linear algebra in Python. We will discuss an important function provided by NumPy that helps us do linear algebra.

This article will discuss NumPy reshape in Python. We will start our discussion with a quick intro about NumPy. Afterwards, we will discuss NumPy reshape in python. Here, we will discuss its syntax, parameters and some examples of reshaping. We will also discuss some special cases of NumPy reshape in python, which includes working with unknown dimensions and flattening the array. So without any further ado, let's get started!

Introduction to NumPy library

NumPy stands for Numerical Python. NumPy is a python library. It is used to work in areas of linear algebra, such as arrays, matrices, Fourier transformation etc. It is an open-source project, and we heavily rely on NumPy for data science projects.

We don't have an array data structure in Python. We use lists in Python, which are equivalent to arrays in general. However, lists take a long time to execute. NumPy aims to offer array objects that are much faster than conventional Python lists. The NumPy array object is referred to as ndarray. It also has several supporting methods that make using ndarray relatively simple.

Connect with our expert counsellors to understand how to hack your way to success

User rating 4.7/5

1:1 doubt support

95% placement record

Akash Pal

Senior Software Engineer

326% Hike After Job Bootcamp

Himanshu Gusain

Programmer Analyst

32 LPA After Job Bootcamp

After Job Bootcamp

What is NumPy/reshape() function

The NumPy reshape in Python is a NumPy library function. It is used to change the shape of an array. The number of elements in each dimension determines the shape of an array. For example, an array {[1,2,3,4], [5,6,7,8]} is a 2 dimension array.

We can add or remove dimensions or vary the number of elements in each dimension by reshaping. For example, changing the above 2D array in a 1D array.

How is it used and why?

The NumPy reshape in python is a reshaping function. The reshaping process includes two steps. The first is to unroll the array to form a straight line. Afterwards, roll the array back up into the new desired shape.

Why use NumPy reshape in Python?

We use NumPy reshape in Python because it helps us modify/reshape arrays according to our choice. It can help us by using the same memory space of the predefined array. We do not have to initialise a new array for every operation. We can use the same memory space wherever we want.

Syntax and Parameter

The syntax of the NumPy reshape function is as follows.

numpy.reshape(array a, newshape (x,y,z), order='C')

The parameters present here are,

Array a: It is the array taken as input, which is to be reshaped. It is a required field.

Newshape (x,y,z): The new shape must be compatible with the old shape. If the value is an integer, the outcome will be a 1-D array of that length. One dimension of a form can be -1. The value is derived from the array's size and remaining dimensions in this scenario. It is a required field.

Order = 'C': The index order reads the array a's items. It then arranges the elements into the reshaped array.

'C' indicates that the items will be read/written in C-like index order, with the final axis index changing the fastest and the first axis index changing the slowest.

'F' indicates that the items will be read and written in Fortran-like index order, with the first index changing the fastest and the last index changing the slowest.

It's worth noting that the 'C' and 'F' options ignore the underlying array's memory layout and solely pertain to the indexing sequence.

If Fortran is contiguous in memory, 'A' signifies reading/writing the elements in Fortran-like index order. Otherwise, in C-like order. It is optional, so adding it when you write your program is not compulsory.

Below are some examples of the function NumPy reshape in Python.

2D Array Example

import numpy as ninja
# Using arange attribute, making array of 12 elements
# The 'numpy' module has no attribute 'arrange'
originalarray = ninja.arange(12)
print("Original array :\n", originalarray)
# Reshaping array into 3 rows and 4 columns
reshapedarray1 = ninja.arange(12).reshape(3, 4)
print("\nReshaped array with 3 rows and 4 columns :\n\n",reshapedarray1)
# Reshaping array into 4 rows and 3 columns
reshapedarray2 = ninja.arange(12).reshape(4, 3)
print("\nReshaped array with 4 rows and 3 columns :\n",reshapedarray2)

Output:

Explanation:

In the above program, we use the 'arange' attribute to make an array of 12 elements. We then use the reshape function to create new arrays of different dimensions. The other dimensions are included in the newshape field of the function. The 12-element array is first reshaped in a 2D array of 3 rows and 4 columns. Afterwards, it is reshaped in another 2D array of 4 rows and 3 columns.

3D Array Example

import numpy as ninja
# Using arange attribute, making array of 12 elements
# The 'numpy' module has no attribute 'arrange'
originalarray = ninja.arange(12)
print("Original array :\n", originalarray)
# Constructing the 3D array
threedarray = ninja.arange(12).reshape(2, 3, 2)
print("\nReshaped array, Original to 3D : \n",
threedarray)

Output:

Explanation:

Similar to what we had seen in the 2D array example. In the above program, we use the 'arange' attribute to make an array of 12 elements. We then use the reshape function to create new arrays of different dimensions. The other dimensions are included in the newshape field of the function. The 12-element array is then reshaped into a 3D array accordingly.

Using Index Order

import numpy as ninja
# Using arange attribute, making array of 8 elements
# The 'numpy' module has no attribute 'arrange'
originalarray = ninja.arange(8)
print("Original array :\n", originalarray)
# Reshaping array into 4 rows and 2 columns by using C index order
reshapedarray1 = ninja.arange(8).reshape(4, 2, order='c')
print("\nReshaped array with 4 rows and 2 columns by using C index order:\n",reshapedarray1)

Output:

Explanation:

Similar to what we had seen in the 2D and 3D array examples. In the above program, we use the 'arange' attribute to make an array of 8 elements. We then use the reshape function to create new arrays of different dimensions. Here, we use the ‘C’ index order to unroll and roll the array into different dimensions. The other dimensions are included in the newshape field of the function. This is why the output array consists of 4 rows and 2 columns.

Unknown Dimension

We can have one “unknown” dimension in our function. It means we do not need to provide an exact integer for one of the dimensions in the reshape method.

We can pass -1 in its place, and NumPy will do the rest accordingly.

Example:

import numpy as ninja
# Using arange attribute, making array of 12 elements
# The 'numpy' module has no attribute 'arrange'
originalarray = ninja.arange(12)
print("Original array :\n", originalarray)
# Converting 1D array into 3D array
reshapedarray1 = ninja.arange(12).reshape(3,4,-1)
print("\nConverted array :\n\n",reshapedarray1)

Output:

Explanation:

The above program converted a 1D array into a 3D array. We had specified two dimensions here, and the next one is marked unknown, i.e., -1. The NumPy reshape in Python was able enough to do the reshaping. It then provided us with a result without causing any errors.

Flattening the Array

Using NumPy reshape in Python, we can flatten a 2D or a 3D array into a 1D array. We need to use reshape(-1) to do this.

Example:

import numpy as ninja
# Using arange attribute, making array of 12 elements
# The 'numpy' module has no attribute 'arrange'
twodarray = ninja.array([[1, 2, 3], [4, 5, 6]])
print("2D Array :\n", twodarray)
# Flattening 2D array into 1D array
flattenedarray = twodarray.reshape(-1)
print("\nFlattened array :\n",flattenedarray)

Output:

Explanation:

The above program converted a 2D array into a 1D array. We use the reshape(-1) function to do so. This function flattens any multi-dimensional array into a linear array. Check out this problem - Maximum Product Subarray

NumPy has the advantage of being computationally very quick. It also uses significantly less memory than lists and can handle a variety of data types.

How do you select a random integer from an array or list in Python?

The choice() function can be used to select random elements from an array.

Is NumPy a package or a module?

NumPy is a Python-based array-processing library. It includes a high-performance multidimensional array object as well as utilities for manipulating these arrays. It is the core Python library for scientific computing.

Is there a size restriction for NumPy arrays?

In NumPy, there is no maximum array size.

What is an axis in NumPy?

The directions along the rows and columns are represented using NumPy axes. NumPy arrays, like coordinate systems, have axes. The axes in a 2-dimensional NumPy array are the directions along the rows and columns.

Conclusion

This article briefly discussed NumPy reshape in Python. We started our discussion with a quick intro about NumPy. Afterwards, we discussed NumPy reshape in python. We discussed its syntax, parameters and some examples of reshaping. We also discussed some special cases of NumPy reshape in python, which includes flattening the array and working with unknown dimensions.

We hope this blog has helped you understand NumPy reshape in Python. If you like to learn more, you can check out our articles: