← Back to NumPy Course | Chapter 5: Array Manipulation | Lesson 1 of 7

reshape()

reshape() rearranges the same numbers into a different grid layout.

In this page:

  1. reshape()
Syntax
python
arr.reshape(new_shape)
arr.reshape(rows, -1)

reshape()

reshape gives the same data a new shape as long as the total element count matches. Use -1 for one dimension and NumPy will work it out. When possible the result is a view of the original data.

Note: Only one dimension can be -1 in a single reshape call.

Example: reshape()

python
import numpy as np

a = np.arange(12)
print(a.reshape(3, 4))
print(a.reshape(2, -1).shape)
print(a.reshape(2, 2, 3).shape)

# Output:
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
# (2, 6)
# (2, 2, 3)
Related Topics
Common Mistakes
  1. Choosing a shape whose product differs from size
  2. Using -1 more than once
  3. Forgetting reshape returns a new array object
Chapter Summary
  • reshape keeps the data but changes the shape
  • Total size must match
  • -1 infers one dimension
  • Often returns a view
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.