NumPy Reshape

What is numpy.reshape()?

numpy.reshape() is a function in NumPy that allows you to change the shape of an existing array without modifying its data. It is one of the most powerful functions in NumPy for transforming the structure of an array while keeping its contents intact. This function is essential in data manipulation, machine learning, and deep learning where different models and operations require inputs in specific shapes.

Why do we need numpy.reshape()?

When working with NumPy arrays, we often need to adjust their shape to fit certain operations or algorithms. For example:

  • Machine learning models require specific input shapes.
  • Matrix operations often require different dimensions.
  • Data preprocessing may involve restructuring arrays for better handling.
  • Certain mathematical computations require reshaped arrays for efficiency.

How does numpy.reshape() work?

The numpy.reshape() function takes an array and a tuple that defines the desired shape. The number of elements in the original array must match the total elements in the reshaped array.

Example:

python
1
2
3
4
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped_arr = arr.reshape(2, 3)
print(reshaped_arr)

Output:

1
2
[[1 2 3]
 [4 5 6]]

Explanation:

  • The original array [1, 2, 3, 4, 5, 6] has 6 elements.
  • The new shape (2,3) means 2 rows and 3 columns.
  • The function rearranges the elements row-wise while maintaining order.

Syntax of numpy.reshape()

Understanding the syntax of numpy.reshape() is crucial for utilizing it effectively. The basic syntax is:

python
1
numpy.reshape(arr, newshape, order='C')

Breakdown of the Syntax:

  1. arr: The NumPy array that needs to be reshaped.
  2. newshape: A tuple defining the desired shape. This must be compatible with the total number of elements in arr.
  3. order (optional): Specifies how elements are read and placed:
    • 'C' (default): Row-wise (C-style order).
    • 'F': Column-wise (Fortran-style order).
    • 'A': Adapts based on input array storage.

Example:

python
1
2
3
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped_arr = np.reshape(arr, (3, 2), order='F')
print(reshaped_arr)

Output:

1
2
3
[[1 4]
 [2 5]
 [3 6]]

Explanation:

  • The original array has 6 elements.
  • The shape (3,2) means 3 rows and 2 columns.
  • The 'F' order fills the elements column-wise instead of row-wise.

Parameters of numpy.reshape()

When using numpy.reshape(), it is important to understand the parameters that control how reshaping works.

Parameters:

  • arr: The input array that needs reshaping.
  • newshape: Defines the new shape of the array. The total number of elements must remain constant.
  • order (optional): Determines how elements are read and placed in the reshaped array.

Example:

python
1
2
3
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped_arr = arr.reshape((2, 3), order='C')
print(reshaped_arr)

Output:

1
2
[[1 2 3]
 [4 5 6]]

Explanation:

  • The array is reshaped into 2 rows and 3 columns.
  • The default 'C' order places elements row-wise.

Reshape From 1-D to 2-D

A one-dimensional (1D) array can be converted into a two-dimensional (2D) array using reshape().

Example:

Original Shape: 1D array with 6 elements.
Target Shape: (2, 3) → 2 rows and 3 columns.
Elements Arrangement: Elements are filled row-wise (default C-order).
Important Note: The total number of elements (6) must remain the same.

python
1
2
3
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped_arr = arr.reshape(2, 3)
print(reshaped_arr)

Example Explanation:

  • The original array: [1, 2, 3, 4, 5, 6]
  • After reshaping:
1
2
[[1 2 3]
 [4 5 6]]
  • The first row gets [1, 2, 3], the second row gets [4, 5, 6].

Reshape From 1-D to 3-D

A one-dimensional (1D) array can be converted into a three-dimensional (3D) array using reshape().

Example:

Original Shape: 1D array with 6 elements.
Target Shape: (2, 1, 3) → 2 blocks, each containing 1 row and 3 columns.
Elements Arrangement: Default row-wise filling (C-order).
Important Note: The total number of elements must remain the same.

python
1
2
3
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped_arr = arr.reshape(2, 1, 3)
print(reshaped_arr)

Output:

python
1
2
[[[1 2 3]]
 [[4 5 6]]]

Can We Reshape Into Any Shape?

No, reshaping is only possible if the total number of elements remains the same. Otherwise, it will raise an error.

Example (Invalid Reshape):

❌ No, reshaping is only possible if the total number of elements remains the same.
❌ Mismatch in elements will cause an error.

python
1
2
3
arr = np.array([1, 2, 3, 4, 5, 6])
# This will raise an error
reshaped_arr = arr.reshape(2, 4)

Example Explanation:

  • Original array has 6 elements.
  • Trying to reshape into (2, 4) requires 8 elements, which is not possible.
  • This results in a ValueError.
Always ensure: original size = target shape size.

Returns Copy or View?

The reshape() function returns a view if possible; otherwise, it creates a copy.

Example:

✅ If possible, reshape() returns a view of the original array (no new memory is allocated).
✅ If a view is not possible, it returns a copy (new memory is allocated).
✅ Modifying the reshaped array may modify the original array if it's a view.

python
1
2
3
4
arr = np.array([1, 2, 3, 4])
reshaped_arr = arr.reshape(2, 2)
reshaped_arr[0, 0] = 99
print(arr)

Example Explanation:

  • reshaped_arr is a view of arr (if possible).
  • Changing reshaped_arr[0,0] = 99 affects arr because it's a view.
  • Original array after modification: [99, 2, 3, 4].
1
[99  2  3  4]

Unknown Dimension

Using -1, NumPy automatically determines the missing dimension.

Example:

python
1
2
3
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped_arr = arr.reshape(2, -1)
print(reshaped_arr)

Example Explanation:

  • Original array: [1, 2, 3, 4, 5, 6]
  • Reshaping using (2, -1): NumPy calculates -1 as 3 (since 6/2 = 3).

Output:

python
1
2
[[1 2 3]
 [4 5 6]]
  • Equivalent to reshape(2,3).

Takeaways for numpy.reshape()

✔ Always maintain the total number of elements when reshaping.
✔ Reshaping can be done in row-major ('C') or column-major ('F') order.
Using -1 allows automatic dimension inference.
Reshape may return a view or copy depending on memory layout.
Attempting an incompatible reshape results in an error.

Frequently Asked Questions