Welcome to Part 3 of Introducing NumPy, a primer for those latest to this essential Python library. Part 1 introduced NumPy arrays and the right way to create them. Part 2 covered indexing and slicing arrays. Part 3 will show you the right way 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 alter the form of arrays, transpose arrays (invert columns with rows), and swap axes. You’ve already been working with the reshape()
method on this series.
One thing to pay attention to with reshape()
is that, like all NumPy assignments, it creates a view of an array slightly than a copy. In the next example, reshaping the arr1d
array produces only a short lived 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 beneficial when you need to temporarily change the form of the array to be used in a…