Open In App

Reshape NumPy Array

Last Updated : 20 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. Numpy is basically used for creating array of n dimensions.
Reshaping numpy array simply means changing the shape of the given array, shape basically tells the number of elements and dimension of array, by reshaping an array we can add or remove dimensions or change number of elements in each dimension.
In order to reshape a numpy array we use reshape method with the given array. 
 

Syntax : array.reshape(shape)
Argument : It take tuple as argument, tuple is the new shape to be formed
Return : It returns numpy.ndarray
 

Note : We can also use np.reshape(array, shape) command to reshape the array
Reshaping : 1-D to 2D 
In this example we will reshape the 1-D array of shape (1, n) to 2-D array of shape (N, M) here M should be equal to the n/N there for N should be factor of n. 
 

Python3




# importing numpy
import numpy as np
 
# creating a numpy array
array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
 
# printing array
print("Array : " + str(array))
 
# length of array
n = array.size
 
# N-D array N dimension
N = 4
 
# calculating M
M = n//N
 
# reshaping numpy array
# converting it to 2-D from 1-D array
reshaped1 = array.reshape((N, M))
 
# printing reshaped array
print("First Reshaped Array : ")
print(reshaped1)
 
# creating another reshaped array
reshaped2 = np.reshape(array, (2, 8))
 
# printing reshaped array
print("Second Reshaped Array : ")
print(reshaped2)


Output : 
 

Array : [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16]
First Reshaped Array : 
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]]
Second Reshaped Array : 
[[ 1  2  3  4  5  6  7  8]
 [ 9 10 11 12 13 14 15 16]]

Reshaping : 1-D to 3-D 
In this we will see how we can reshape a 1-D array to 3-D dimension array. A 3-D array is the 1-D array of 2-D arrays. 
 

Python3




# importing numpy
import numpy as np
 
# creating a numpy array
array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
 
# printing array
print("Array : " + str(array))
 
 
# reshaping numpy array
# converting it to 3-D from 1-D array
reshaped = array.reshape((2, 2, 4))
 
# printing reshaped array
print("Reshaped 3-D Array : ")
print(reshaped)


Output : 
 

Array : [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16]
Reshaped 3-D Array : 
[[[ 1  2  3  4]
  [ 5  6  7  8]]

 [[ 9 10 11 12]
  [13 14 15 16]]]

Reshaping N-D to 1-D array 
In this example we will see how we can reshape a 2-D or 3-D array to form a 1-D array. We can also use reshape(-1) to do this, here -1 is the unknown dimension. 
 

Python3




# importing numpy
import numpy as np
 
# creating a numpy array
array = np.array([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]])
 
# printing array
print(" 2-D Array : ")
print(array)
 
 
# reshaping numpy array
# converting it to 1-D from 2-D array
reshaped = array.reshape((9))
 
# or we can use unknown dimension
# reshaped = array.reshape((-1))
 
# printing reshaped array
print("Reshaped 1-D Array : ")
print(reshaped)


Output : 
 

 2-D Array : 
[[1 2 3]
 [4 5 6]
 [7 8 9]]
Reshaped 1-D Array : 
[[1 2 3 4 5 6 7 8 9]]

Reshaping using unknown dimension 
We can reshape a array although we don’t know all the new dimensions by using -1 as one of the dimension, but we should know all the other dimension to use unknown dimension 
 

Python3




# importing numpy
import numpy as np
 
# creating a numpy array
array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
 
# printing array
print("Array : " + str(array))
 
 
# reshaping numpy array
# converting it to 3-D from 1-D array
reshaped1 = array.reshape((2, 2, -1))
 
# printing reshaped array
print("First Reshaped Array : ")
print(reshaped1)
 
 
# converting it to 2-D array
reshaped2 = array.reshape((4, -1))
 
# printing reshaped array
print("Second Reshaped Array : ")
print(reshaped2)


Output : 
 

Array : [ 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16]
First Reshaped Array : 
[[[ 1  2  3  4]
  [ 5  6  7  8]]

 [[ 9 10 11 12]
  [13 14 15 16]]]
Second Reshaped Array : 
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]]

Errors Occur during reshaping 
When we try to reshape a array to a shape which is not mathematically possible then value error is generated saying can not reshape the array. For example when we try to reshape 1-D array with 4 elements into a 2-D array of dimension(3, 3) is not possible as new array requires 9 elements 
 

Python3




# importing numpy
import numpy as np
 
# creating a numpy array
array = np.array([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]])
 
# printing array
print(" 2-D Array : ")
print(array)
 
 
# reshaping numpy array
# converting it to 1-D from 2-D array
# reshaping it into 1, 5
reshaped = array.reshape((1, 5))
 
# or we can use
 
# printing reshaped array
print("Reshaped 1-D Array : ")
print(reshaped)


ValueError: cannot reshape array of size 9 into shape (1, 5)


Previous Article
Next Article

Similar Reads

Numpy Reshape 2D To 3D Array
NumPy is a powerful library in Python used for numerical operations and data analysis. Reshaping arrays is a common operation in NumPy, and it allows you to change the dimensions of an array without changing its data. In this article, we'll discuss how to reshape a 2D NumPy array into a 3D array. Understanding 2D and 3D ArraysA 2D array is a collec
3 min read
Python | Numpy matrix.reshape()
With the help of Numpy matrix.reshape() method, we are able to reshape the shape of the given matrix. Remember all elements should be covered after reshaping the given matrix. Syntax : matrix.reshape(shape) Return: new reshaped matrix Example #1 : In the given example we are able to reshape the given matrix by using matrix.reshape() method. # impor
1 min read
Numpy MaskedArray.reshape() function | Python
numpy.MaskedArray.reshape() function is used to give a new shape to the masked array without changing its data.It returns a masked array containing the same data, but with a new shape. The result is a view on the original array; if this is not possible, a ValueError is raised. Syntax : numpy.ma.reshape(shape, order) Parameters: shape:[ int or tuple
3 min read
Difference between reshape() and resize() method in Numpy
Both the numpy.reshape() and numpy.resize() methods are used to change the size of a NumPy array. The difference between them is that the reshape() does not changes the original array but only returns the changed array, whereas the resize() method returns nothing and directly changes the original array. Example 1: Using reshape() C/C++ Code # impor
1 min read
What does -1 mean in numpy reshape?
While working with arrays many times we come across situations where we need to change the shape of that array but it is a very time-consuming process because first, we copy the data and then arrange it into the desired shape, but in Python, we have a function called reshape() for this purpose. What is numpy.reshape() in Python The numpy.reshape()
3 min read
numpy.reshape() in Python
The numpy.reshape() function shapes an array without changing the data of the array. Syntax: numpy.reshape(array, shape, order = 'C') Parameters : array : [array_like]Input array shape : [int or tuples of int] e.g. if we are arranging an array with 10 elements then shaping it like numpy.reshape(4, 8) is wrong; we can do numpy.reshape(2, 5) or (5, 2
2 min read
Python | Reshape a list according to given multi list
Given two lists, a single dimensional and a multidimensional list, write Python program to reshape the single dimensional list according to the length of multidimensional list. Examples: Input : list1 = [[1], [2, 3], [4, 5, 6]] list2 = ['a', 'b', 'c', 'd', 'e', 'f'] Output : [['a'], ['b', 'c'], ['d', 'e', 'f']] Input : list1 = [[8, 2, 5], [1], [12,
7 min read
How to reshape Pandas Series?
In this article, we will see how to reshaping Pandas Series. So, for reshaping the Pandas Series we are using reshape() method of Pandas Series object. Syntax: Pandas.Series.values.reshape((dimension)) Return: return an ndarray with the values shape if the specified shape matches exactly the current shape, then return self (for compat) Let's see so
1 min read
Reshape Wide DataFrame to Tidy with identifiers using Pandas Melt
Sometimes we need to reshape the Pandas data frame to perform analysis in a better way. Reshaping plays a crucial role in data analysis. Pandas provide functions like melt and unmelt for reshaping. In this article, we will see what is Pandas Melt and how to use it to reshape wide to Tidy with identifiers. Pandas Melt(): Pandas.melt() unpivots a Dat
3 min read
Reshape a Pandas DataFrame using stack,unstack and melt method
Pandas use various methods to reshape the dataframe and series. Reshaping a Pandas DataFrame is a common operation to transform data structures for better analysis and visualization. The stack method pivots columns into rows, creating a multi-level index Series. Conversely, the unstack method reverses this process by pivoting inner index levels int
4 min read
Practice Tags :