Introducing NumPy, Part 3: Manipulating Arrays | by Lee Vaughan | Sep, 2024


Shaping, transposing, joining, and splitting arrays

A grayscale Rubik’s cube hits itself with a hammer, breaking off tiny cubes.
Manipulating an array as imagined by DALL-E3

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 np

In [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…



Source link

Be the first to comment

Leave a Reply

Your email address will not be published.


*