Welcome to Part 3 of Introducing NumPyan introduction for those new to this essential Python library. Part 1 introduced NumPy arrays and how to create them. Part 2 Indexing and segmentation of matrices was covered. Part 3 will show how to manipulate existing matrices by reshaping them, swapping their axes, and merging and splitting them. These tasks are useful for work such as rotating, enlarging, and translating images and fine-tuning machine learning models.
NumPy comes with methods for changing the shape of matrices, transposing matrices (reversing columns with rows), and swapping axes. You've already been working with the reshape()
method in this series.
One thing to keep in mind with reshape()
is that, like all NumPy assignments, it creates a view of a matrix instead of a CopyIn the following example, by changing the shape of arr1d
The matrix produces only a temporary change in the matrix:
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 temporarily change the shape of the matrix to use it in a…