Learning Objectives – after this chapter you will be able to:
  • Read an array’s shape and explain what each number means.
  • Reshape arrays to different dimensions with reshape().
  • Use -1 to let NumPy calculate one dimension.
  • Flatten arrays and transpose matrices.
Shape of an Array

The shape attribute is a tuple giving the number of elements along each dimension (axis). For a 2-D array it is (rows, columns).

import numpy as np

print(np.array([1, 2, 3, 4]).shape)
print(np.array([[1, 2, 3], [4, 5, 6]]).shape)
print(np.zeros((2, 3, 4)).shape)

arr = np.array([1, 2, 3, 4], ndmin=3)   # force at least 3 dimensions
print(arr, arr.shape)
Output
(4,)
(2, 3)
(2, 3, 4)
[[[1 2 3 4]]] (1, 1, 4)
Reshaping Arrays

reshape(new_shape) changes the number of rows/columns/dimensions without changing the data. The rule: the total number of elements must stay the same (e.g. 12 = 3 × 4 = 2 × 6 = 2 × 3 × 2).

import numpy as np

arr = np.arange(1, 13)
print(arr.reshape(3, 4))
print(arr.reshape(2, 3, 2))
print(arr.reshape(2, 6).ndim)
Output
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]
[[[ 1  2]
  [ 3  4]
  [ 5  6]]

 [[ 7  8]
  [ 9 10]
  [11 12]]]
2
The total size must match
import numpy as np

arr = np.arange(1, 13)
try:
    arr.reshape(5, 3)
except ValueError as e:
    print("ValueError:", e)
Output
ValueError: cannot reshape array of size 12 into shape (5,3)
Unknown Dimension: -1

You may give one dimension as -1; NumPy calculates it from the array’s size.

import numpy as np

arr = np.arange(1, 13)
print(arr.reshape(4, -1).shape)     # 12 / 4 = 3 columns
print(arr.reshape(-1, 6).shape)     # 12 / 6 = 2 rows
print(arr.reshape(2, 2, -1).shape)
print(arr.reshape(-1, 1).shape)     # a column vector
Output
(4, 3)
(2, 6)
(2, 2, 3)
(12, 1)
Flattening: reshape(-1), ravel() and flatten()

Flattening converts a multi-dimensional array into 1-D.

import numpy as np

m = np.array([[1, 2, 3], [4, 5, 6]])
print(m.reshape(-1))
print(m.ravel())        # view when possible
f = m.flatten()         # always a copy
f[0] = 100
print(m[0, 0], f[0])
Output
[1 2 3 4 5 6]
[1 2 3 4 5 6]
1 100
reshape() returns a view whenever possible, so changing the reshaped array can change the original. Use .copy() if you need independent data.
Transpose

The transpose (arr.T or np.transpose(arr)) swaps rows and columns: shape (2, 3) becomes (3, 2).

import numpy as np

m = np.array([[1, 2, 3], [4, 5, 6]])
print(m.T)
print(m.shape, m.T.shape)
Output
[[1 4]
 [2 5]
 [3 6]]
(2, 3) (3, 2)
Key Takeaways
  • shape lists the size of each axis; for 2-D it is (rows, columns).
  • reshape() keeps the same number of elements; one dimension may be -1.
  • ravel() gives a view when possible, flatten() always copies; .T transposes.
Video : Array Shape and Reshape
Question / Answer (15 questions)

Answer : shape is a tuple giving the number of elements along each dimension (axis). For a 2-D array it is (rows, columns); for example a 2 × 3 matrix has shape (2, 3).

Answer : (4,) – a tuple with one value. The trailing comma shows it is a one-element tuple.

Answer : ndmin specifies the minimum number of dimensions. np.array([1, 2, 3, 4], ndmin=3) produces shape (1, 1, 4).

Answer : Reshaping changes the shape (number of dimensions or elements per dimension) of an array without changing its data, using reshape().

Answer : The total number of elements must remain the same. An array of 12 elements can be reshaped to (3, 4), (2, 6) or (2, 3, 2), but not to (5, 3).

Answer : NumPy raises ValueError, e.g. "cannot reshape array of size 12 into shape (5,3)".

Answer : -1 stands for an unknown dimension that NumPy calculates automatically from the array size. Only one dimension can be -1. arr.reshape(4, -1) for 12 elements gives shape (4, 3).

Answer : Use arr.reshape(-1), arr.ravel() or arr.flatten().

Answer : ravel() returns a flattened view of the original data whenever possible, so it is fast but changes may affect the original. flatten() always returns a new copy, so changes never affect the original.

Answer : reshape() returns a view whenever the memory layout allows it; otherwise it returns a copy. Modifying a reshaped view changes the original array.

Answer : The transpose swaps rows and columns, so element (i, j) moves to (j, i). Use arr.T or np.transpose(arr); a (2, 3) array becomes (3, 2).

Answer : arr.reshape(-1, 1), giving shape (12, 1) – 12 rows and 1 column.

Answer : np.arange(1, 13).reshape(3, 4) gives [[1 2 3 4] [5 6 7 8] [9 10 11 12]].

Answer : shape is (2, 3, 4) and size is 2 × 3 × 4 = 24.

Answer : Many algorithms and libraries expect data in a specific shape, for example a 2-D (samples × features) matrix or a column vector, and images are often reshaped between 2-D and 1-D forms. reshape() converts data without copying where possible.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. An array has 12 elements. Which reshape is INVALID?

Show Answer

Correct Answer : C. (5, 2)
5 × 2 = 10, not 12.

Q2. np.arange(8).reshape(2, -1).shape is:

Show Answer

Correct Answer : A. (2, 4)
8 / 2 = 4 columns.

Q3. Which method ALWAYS returns a copy when flattening?

Show Answer

Correct Answer : C. flatten()
flatten() always copies; ravel() and reshape() return views when possible.

Q4. What is the shape of the transpose of an array with shape (2, 5)?

Show Answer

Correct Answer : D. (5, 2)
Transposing swaps the two axes.

Q5. How many dimensions can be given as -1 in one reshape() call?

Show Answer

Correct Answer : A. Only one
NumPy can infer only one unknown dimension.

Bibliography/References

The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.

  1. NumPy Developers. (n.d.). numpy.reshape. NumPy API Reference. https://numpy.org/doc/stable/reference/generated/numpy.reshape.html
  2. NumPy Developers. (n.d.). NumPy quickstart. NumPy User Guide. https://numpy.org/doc/stable/user/quickstart.html
  3. NumPy Developers. (n.d.). The N-dimensional array (ndarray). NumPy Reference. https://numpy.org/doc/stable/reference/arrays.ndarray.html
  4. NumPy Developers. (n.d.). Copies and views. NumPy User Guide. https://numpy.org/doc/stable/user/basics.copies.html
  5. VanderPlas, J. (2016). Python Data Science Handbook. O’Reilly Media. (Free online edition.) https://jakevdp.github.io/PythonDataScienceHandbook/