- Read an array’s
shapeand explain what each number means. - Reshape arrays to different dimensions with
reshape(). - Use
-1to 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)
(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)
[[ 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
import numpy as np
arr = np.arange(1, 13)
try:
arr.reshape(5, 3)
except ValueError as e:
print("ValueError:", e)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
(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])
[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)
[[1 4] [2 5] [3 6]] (2, 3) (3, 2)
Key Takeaways
shapelists 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;.Ttransposes.
Video : Array Shape and Reshape
Question / Answer (15 questions)
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.
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.
- NumPy Developers. (n.d.). numpy.reshape. NumPy API Reference. https://numpy.org/doc/stable/reference/generated/numpy.reshape.html
- NumPy Developers. (n.d.). NumPy quickstart. NumPy User Guide. https://numpy.org/doc/stable/user/quickstart.html
- NumPy Developers. (n.d.). The N-dimensional array (ndarray). NumPy Reference. https://numpy.org/doc/stable/reference/arrays.ndarray.html
- NumPy Developers. (n.d.). Copies and views. NumPy User Guide. https://numpy.org/doc/stable/user/basics.copies.html
- VanderPlas, J. (2016). Python Data Science Handbook. O’Reilly Media. (Free online edition.) https://jakevdp.github.io/PythonDataScienceHandbook/