0
0
NumpyHow-ToBeginner ยท 3 min read

How to Reshape Array in NumPy: Syntax and Examples

Use the numpy.reshape() function to change the shape of an array without changing its data. Provide the new shape as a tuple, for example, array.reshape((rows, columns)). The total number of elements must remain the same.
๐Ÿ“

Syntax

The basic syntax to reshape a NumPy array is:

  • array.reshape(new_shape): Returns a new array with the specified shape.
  • new_shape is a tuple indicating the desired dimensions, e.g., (2, 3) for 2 rows and 3 columns.
  • The total number of elements before and after reshaping must be the same.
python
reshaped_array = array.reshape(new_shape)
๐Ÿ’ป

Example

This example shows how to reshape a 1D array of 6 elements into a 2D array with 2 rows and 3 columns.

python
import numpy as np

array = np.array([1, 2, 3, 4, 5, 6])
reshaped_array = array.reshape((2, 3))
print(reshaped_array)
Output
[[1 2 3] [4 5 6]]
โš ๏ธ

Common Pitfalls

Common mistakes when reshaping arrays include:

  • Trying to reshape to a shape with a different total number of elements, which causes an error.
  • Forgetting that reshape returns a new array and does not change the original array unless reassigned.
  • Using -1 incorrectly; it can be used to automatically calculate one dimension but only once.
python
import numpy as np

array = np.array([1, 2, 3, 4, 5, 6])

# Wrong: total elements mismatch
# reshaped = array.reshape((3, 3))  # This will raise an error

# Correct: using -1 to infer dimension
reshaped = array.reshape((3, -1))
print(reshaped)
Output
[[1 2] [3 4] [5 6]]
๐Ÿ“Š

Quick Reference

FunctionDescriptionExample
reshapeChange array shape without changing dataarray.reshape((2, 3))
-1 in reshapeAutomatically calculate one dimensionarray.reshape((3, -1))
flattenConvert multi-dimensional array to 1Darray.flatten()
โœ…

Key Takeaways

Use numpy.reshape() to change the shape of an array while keeping data intact.
The new shape must have the same total number of elements as the original array.
Use -1 in reshape to let NumPy infer one dimension automatically.
reshape returns a new array; assign it to a variable to keep the result.
Mismatched shapes cause errors, so always check element counts before reshaping.