Copy a numpy.array without modifying the original

Asked

Viewed 827 times

7

Given a numpy.array as the next:

r = np.arange(36)
r.resize(6, 6)

Which results in:

array([[ 0,  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 when I just want to copy a piece of this array, for example:

r2 = r[:3,:3]

Which results in:

array([[ 0,  1,  2],
       [ 6,  7,  8],
       [12, 13, 14]])

If I modify the array r2 then the array r is also modified:

r2[:] = 0

Now the array r is:

[[ 0  0  0  3  4  5]
 [ 0  0  0  9 10 11]
 [ 0  0  0 15 16 17]
 [18 19 20 21 22 23]
 [24 25 26 27 28 29]
 [30 31 32 33 34 35]]

So I’d like to know how to copy r2 so that if I modify it, do not change the original array r.

1 answer

2


You must make a copy so that r2 so that it does not point to the same object:

import numpy

r = numpy.arange(36)
r.resize(6,6)
r2 = numpy.copy(r[:3,:3])
r2[:] = 0

Making print(r) the output will be:

[[ 0  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 the output of print(r2):

[[0 0 0]
 [0 0 0]
 [0 0 0]]

As you can see, you can "move" as you please r2 without r be affected.

numpy.copy DOCUMENTATION

Related: http://www.python-course.eu/deep_copy.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.