NumPy ndarray.reshape()
The numpy.ndarray.reshape()
method allows changing the shape of a NumPy array without altering its data. It returns a new view of the original array whenever possible, or a copy if required.
Syntax
ndarray.reshape(shape, /, *, order='C', copy=None)
Parameters
Parameter | Type | Description |
---|---|---|
shape | int or tuple of ints | The new shape for the array. It must be compatible with the original size. |
order | {‘C’, ‘F’, ‘A’} | Memory layout order: – ‘C’ (row-major, C-style, default) – ‘F’ (column-major, Fortran-style) – ‘A’ (Fortran-like if input is Fortran-contiguous, otherwise C-like) |
copy | bool, optional | Whether to create a copy of the data. Defaults to None , meaning it only copies if needed. |
Return Value
Returns an array with the specified shape. If possible, it provides a view of the original array; otherwise, it creates a new copy.
Examples
1. Basic Reshaping of a 1D Array
Converting a 1D array into a 2D array of shape (3, 2).
import numpy as np
# Creating a 1D array with 6 elements
arr = np.array([1, 2, 3, 4, 5, 6])
# Reshaping into a 2D array with 3 rows and 2 columns
reshaped_arr = arr.reshape((3, 2))
print(reshaped_arr)
Output:
[[1 2]
[3 4]
[5 6]]
2. Using -1 to Auto-Calculate One Dimension
Using -1
lets NumPy automatically compute one dimension while maintaining the total size.
import numpy as np
# Original 1D array with 12 elements
arr = np.arange(12)
# Reshaping into a 3-row array with auto-computed columns
reshaped_arr = arr.reshape((3, -1))
print(reshaped_arr)
Output:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
3. Reshaping with Fortran (‘F’) Order
Reshaping while filling elements column-wise using Fortran-style ordering.
import numpy as np
# Creating a 1D array with 6 elements
arr = np.array([1, 2, 3, 4, 5, 6])
# Reshaping with Fortran order (column-major)
reshaped_arr = arr.reshape((3, 2), order='F')
print(reshaped_arr)
Output:
[[1 4]
[2 5]
[3 6]]
Elements are filled column-wise instead of row-wise as in C-order.
4. Ensuring a Copy of the Array
Using the copy
parameter to force a copy instead of a view.
import numpy as np
# Creating a 1D array
arr = np.array([1, 2, 3, 4, 5, 6])
# Reshaping with a forced copy
reshaped_arr = arr.reshape((2, 3), copy=True)
# Modifying the original array
arr[0] = 99
print("Original Array:")
print(arr)
print("Reshaped Array:")
print(reshaped_arr)
Output:
Original Array:
[99 2 3 4 5 6]
Reshaped Array:
[[1 2 3]
[4 5 6]]
The reshaped array remains unchanged when modifying the original array, confirming that a copy was created.