Welcome to Part 3 of Introducing NumPy, a primer for those new to this essential Python library. Part 1 introduced NumPy arrays and how to create them. Part 2 covered indexing and slicing arrays. Part 3 will show you how to manipulate existing arrays by reshaping them, swapping their axes, and merging and splitting them. These tasks are handy for jobs like rotating, enlarging, and translating images and fitting machine learning models.
NumPy comes with methods to change the shape of arrays, transpose arrays (invert columns with rows), and swap axes. You’ve already been working with the reshape()
method in this series.
One thing to be aware of with reshape()
is that, like all NumPy assignments, it creates a view of an array rather than a copy. In the following example, reshaping the arr1d
array produces only a temporary change to the array:
In [1]: import numpy as npIn [2]: arr1d = np.array([1, 2, 3, 4])
In [3]: arr1d.reshape(2, 2)
Out[3]:
array([[1, 2],
[3, 4]])
In [4]: arr1d
Out[4]: array([1, 2, 3, 4])
This behavior is useful when you want to temporarily change the shape of the array for use in a…