Skip to content
Home » numpy Part 8 – How to Copy a numpy Array

numpy Part 8 – How to Copy a numpy Array

Spread the love

Today we’ll learn how to copy a numpy array.

copy a numpy array

If you want to copy an array, you can use either the numpy.copy method or the ndarray.copy method directly on the array.

Here’s an example with the former. Let’s create an array and reshape it to have 7 rows and 5 columns:

>>> a = np.arange(1, 36).reshape(7, 5)
>>> print(a)
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]
 [21 22 23 24 25]
 [26 27 28 29 30]
 [31 32 33 34 35]]

Let’s make a copy:

>>> b = np.copy(a)
>>> print(b)
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]
 [21 22 23 24 25]
 [26 27 28 29 30]
 [31 32 33 34 35]]

Now let’s modify array a. Let’s set all the elements in it to 10.

>>> a[0] = 10
>>> print(a)
[[10 10 10 10 10]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]
 [21 22 23 24 25]
 [26 27 28 29 30]
 [31 32 33 34 35]]

Let’s see whether the copy is still as before:

>>> print(b)
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]
 [21 22 23 24 25]
 [26 27 28 29 30]
 [31 32 33 34 35]]

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

And now let’s see how the other method can be used. Let’s copy the array b:

>>> c = b.copy()
>>> print(c)
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]
 [21 22 23 24 25]
 [26 27 28 29 30]
 [31 32 33 34 35]]

And now let’s modify b:

>>> b[-1, -1] = 100
>>> print(b)
[[  1   2   3   4   5]
 [  6   7   8   9  10]
 [ 11  12  13  14  15]
 [ 16  17  18  19  20]
 [ 21  22  23  24  25]
 [ 26  27  28  29  30]
 [ 31  32  33  34 100]]

So, what does the array c look like now?

>>> print(c)
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]
 [21 22 23 24 25]
 [26 27 28 29 30]
 [31 32 33 34 35]]

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of this article:


Spread the love
Tags:

Leave a Reply