Skip to main content
Documents
basicsArray CreationArray OperationsArray Computation & AnalysisLinear AlgebraRandom ProbabilityData Input/Output & Conversion

NumPy reshape()

The NumPy `reshape()` function is an array operation that changes the shape of an array without altering its data. It allows for transforming an array into a new shape while maintaining the same number of elements.

Usage

The `reshape()` function is used when you need to modify the dimensions of an array to fit a particular structure or to prepare it for operations like matrix multiplication. It helps in organizing data for better computational efficiency.

numpy.reshape(array, new_shape)

In this syntax, `array` represents the original array, and `new_shape` is a tuple defining the desired dimensions. Note that the product of the dimensions in `new_shape` must equal the total number of elements in `array`. If not, a `ValueError` will be raised.

Examples

1. Basic Reshape

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6])
# Reshape 1D array of 6 elements to 2D array with 2 rows and 3 columns
reshaped_arr = np.reshape(arr, (2, 3))

2. Reshape with -1

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
# Let NumPy calculate the number of columns needed for 2 rows
reshaped_arr = np.reshape(arr, (2, -1))

3. Reshape a 3D Array

arr = np.arange(24)
# Reshape 1D array of 24 elements to 3D array with dimensions 2x3x4
reshaped_arr = np.reshape(arr, (2, 3, 4))

Tips and Best Practices

  • Ensure compatibility. The new shape must have the same total number of elements as the original array. A mismatch will result in a `ValueError`.
  • Use `-1` wisely. Let NumPy infer one of the dimensions by setting it to `-1`, simplifying the code.
  • Check for memory order. Be aware of memory layout (`C` vs. `F` order) if performance or specific data arrangements are crucial. Reshaping typically defaults to `C` order, but you can specify `order='F'` if needed for column-major order.
  • Keep data integrity. Reshaping does not change the data itself, only its interpretation.