Karn Kumar
Karn Kumar

Reputation: 8826

Why the original numpy array get changed while changing another array created from it?

i have a numpy array r when i used to create another array r2 out of it and turning that new array r2 to zero it also changed the original array r

I have searched around the similar questions but did not turned around the any satisfying answer for this, so please consider suggesting an appropriate answer.

Original Array:

>>> r
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]])

another numpy array from original array r2 as follows:

>>> r2 = r[:3, :3]
>>> r2
array([[ 0,  1,  2],
       [ 6,  7,  8],
       [12, 13, 14]])

So, When i do set new array to r2 to zero

>>> r2[:]  = 0
>>> r2
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])

So, when i see original array then it also been looked change:

Array Changed after chanin the new array:

>>> r
array([[ 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, 30, 30, 30, 30, 30]])

Happy New Years in advanced, Guys!

Upvotes: 1

Views: 1661

Answers (1)

javan.rajpopat
javan.rajpopat

Reputation: 147

Explanation

r2 = r[:3, :3] 

Doesn't create a new array, but renames the current array. What you need to do is known as 'deep copy'. Use, numpy.copy() to do what you need.

x = np.array([1, 2, 3])
y = x
z = np.copy(x)

x[0] = 10
x[0] == y[0]
True
x[0] == z[0]
False

Read more from,

https://het.as.utexas.edu/HET/Software/Numpy/reference/generated/numpy.copy.html

Upvotes: 2

Related Questions