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!
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.
Syntax
The syntax of the NumPy reshape function is as follows.
numpy.reshape(array a, newshape (x,y,z), order='C')
Parameters
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.
Return Value
The numpy.reshape() function in Python returns a new array with the specified shape, reshaping the original array without changing its data.
Examples of numpy.reshape() Function
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.
Frequently Asked Questions
What does reshape() do in Python?
The reshape() function in Python, particularly in libraries like NumPy, rearranges the dimensions of an array without changing its data, allowing for flexible manipulation of array shapes.
What does reshape(-1, 1) do?
Using reshape(-1, 1) in Python (NumPy) transforms an array into a column vector by inferring the correct number of rows while ensuring one column, useful for tasks like preparing data for machine learning models.
How to reshape 2D array to 1D in Python?
To reshape a 2D array to 1D in Python using NumPy, you can use array.reshape(-1), which flattens the array into a single-dimensional format while preserving all elements sequentially.
How to reshape 2D array to 3D in Python?
To reshape a 2D array to a 3D array in Python with NumPy, use array.reshape(rows, cols, depth) where rows, cols, and depth specify the dimensions of the new 3D array, ensuring all elements are appropriately rearranged.
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: