
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
- NumPy Compiler
NumPy - Reshaping Arrays
Reshaping NumPy Array
By reshaping a NumPy array, we mean to change its shape, i.e., modifying the number of elements along each dimension while keeping the total number of elements the same. In other words, the product of the dimensions in the new shape must equal the product of the dimensions in the original shape.
For instance, an array of shape (6,) can be reshaped to (2, 3) or (3, 2), but not to (2, 2) since 6 elements cannot fit into a 2x2 array.
Reshaping 1D Array to 2D Array
We can reshape a 1-D array to a 2-D array in NumPy using the reshape() function. This is used to organize linear data into a matrix form.
The reshape() function changes the shape of an existing array without changing its data. Following is the syntax −
numpy.reshape(array, newshape)
Where,
array − The array you want to reshape.
newshape − The shape you want to give the array. It can be an integer or a tuple of integers. One dimension can be -1, which means it will be presumed from the length of the array and the remaining dimensions.
Example: Basic Reshaping
In the following example, we are reshaping a 1D array "arr" with "6" elements into a 2D array using the reshape() function −
import numpy as np # Original 1-D array arr = np.array([1, 2, 3, 4, 5, 6]) # Reshape to 2-D array reshaped_arr = arr.reshape((2, 3)) print("1-D to 2-D Array (2x3):") print(reshaped_arr)
Following is the output obtained −
1-D to 2-D Array (2x3): [[1 2 3] [4 5 6]]
Example: Practical Use Case of Reshaping
Imagine you have a list of test scores for students in a class, and you want to organize them into a table where each row represents a student, and each column represents a different test. You can do this by reshaping the 1D array of scores into a 2D array −
import numpy as np # Original 1-D array of test scores scores = np.array([85, 90, 78, 92, 88, 76]) # Reshape into a 2-D array where each row is a student's scores scores_matrix = scores.reshape((2, 3)) print("Scores Matrix (2 students, 3 tests each):") print(scores_matrix)
This will produce the following result −
Scores Matrix (2 students, 3 tests each): [[85 90 78] [92 88 76]]
Reshaping 1D Array to 3D Array
We can also reshape a 1-D array to a 3-D array in NumPy using the reshape() function. This helps you to represent data with more complex structures such as multi-channel images (e.g., RGB images), time-series data across different channels, or volumetric data.
Example
In this example, we are reshaping a 1-D array "arr" with "12" elements into a 3-D array using the reshape() function −
import numpy as np # Original 1-D array arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) # Reshape to 3-D array reshaped_arr = arr.reshape((2, 2, 3)) print("1-D to 3-D Array (2x2x3):") print(reshaped_arr)
Following is the output of the above code −
1-D to 3-D Array (2x2x3): [[[ 1 2 3] [ 4 5 6]] [[ 7 8 9] [10 11 12]]]
Reshaping ND Array to 1D Array
Reshaping an N-Dimensional (N-D) array to a 1-Dimensional (1-D) array in NumPy is a process of flattening or collapsing the multi-dimensional array into a single linear array. We can achieve this as well using the reshape() function.
Flattening complex multi-dimensional arrays into a 1-D format simplifies certain data processing tasks and make the data easier to handle and analyse.
Example
In the example below, we are reshaping a 2-D array "arr" with shape (2, 3) into a 1-D array using the reshape() function with -1 as the argument −
import numpy as np # Original 2-D array arr = np.array([[1, 2, 3], [4, 5, 6]]) # Reshape to 1-D array reshaped_arr = arr.reshape(-1) print("Reshaped Array:", reshaped_arr)
The output obtained is as shown below −
Reshaped Array:[1 2 3 4 5 6]
Reshaping Unknown Dimension Arrays
You can reshape an array with an unknown dimension using the reshape() function in NumPy. By passing -1 as an argument to reshape() function, NumPy automatically calculates the size of that dimension based on the total number of elements in the array and the other specified dimensions.
This helps you to reshape arrays without explicitly computing the exact size of every dimension.
Example
In the following example, we are reshaping a 1-D array arr with "12" elements into a "3-D" array using the reshape() function, specifying one of the dimensions as "-1" −
import numpy as np # Original 1-D array arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) # Reshape to 3-D array with one unknown dimension reshaped_arr = arr.reshape((2, 2, -1)) print("Reshaped Array with Unknown Dimension:") print(reshaped_arr)
After executing the above code, we get the following output −
Reshaped Array with Unknown Dimension: [[[ 1 2 3] [ 4 5 6]][[ 7 8 9] [10 11 12]]]
Error Occurrence while Reshaping Array
Reshaping arrays in NumPy can sometimes lead to errors, especially when the total number of elements does not match the product of the specified dimensions. It is important to ensure that the new shape is compatible with the number of elements in the array.
Common Errors while Reshaping Array
Following are the most common errors that occur while reshaping an array in NumPy −
-
ValueError: Total size of new array must be unchanged − This error occurs when the number of elements in the original array does not match the product of the dimensions specified for reshaping.
For example, trying to reshape a 1-D array of 10 elements into a 3x3 matrix (reshape((3, 3))) will raise this error because 3 3 = 9 which is different from 10.
-
ValueError: cannot reshape array of size X into shape (Y, Z) − This error indicates that the original array size (X) is not compatible with the specified shape (Y, Z).
For instance, trying to reshape a 1-D array of size 10 into a 2x5 matrix (reshape((2, 5))) will raise this error because 2 5 = 10, but the array needs to be 2-dimensional to fit the new shape.
TypeError: 'numpy.ndarray' object cannot be interpreted as an integer − This error occurs when the dimensions provided for reshaping are not integers or are incorrectly specified. Ensure that all dimensions passed to reshape() function are valid integers and that they correctly represent the new shape.
Handling Errors while Reshaping Array
Following are the ways to handle errors that occur while reshaping an array in NumPy −
Check Array Size Before reshaping, verify the size of your original array using array.size() function and ensure it matches the product of the new shape dimensions.
Use -1 for Unknown Dimensions When reshaping, if one dimension is unknown, use -1 to let NumPy calculate it automatically based on the total number of elements in the array.
Catch Exceptions Wrap your reshaping code in a try-except block to catch potential errors and handle them gracefully. This can prevent your program from crashing and allow for appropriate error messaging or fallback actions.
Example
In the following example, we attempt to reshape a 1D array "arr" with 5 elements into a "2x3" 2D array, which results in a ValueError because the total number of elements does not match the specified shape −
import numpy as np # Original 1-D array arr = np.array([1, 2, 3, 4, 5]) try: # Attempt to reshape to an incompatible shape reshaped_arr = arr.reshape((2, 3)) except ValueError as e: print("Error Occurred During Reshaping:") print(e)
The error obtained is as follows −
Error Occurred During Reshaping: cannot reshape array of size 5 into shape (2,3)