Copy a numpy.array without modifying the original

6

Given a numpy.array like the following:

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

That 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 want to copy only a piece of this array, for example:

r2 = r[:3,:3]

That results in:

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

If you 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]]

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

    
asked by anonymous 03.11.2016 / 23:38

1 answer

2

You should make a copy so that r2 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

By doing 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 "tinker" at will with r2 without r being affected.

DOCUMENTATION numpy.copy

Related: link

    
04.11.2016 / 11:18