Introducing NumPy, Part 3: Manipulating Arrays

-

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 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 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 beneficial when you need to temporarily change the form of the array to be used in a…

ASK ANA

What are your thoughts on this topic?
Let us know in the comments below.

0 0 votes
Article Rating
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Share this article

Recent posts

0
Would love your thoughts, please comment.x
()
x