1

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!

Karn Kumar
  • 8,518
  • 3
  • 27
  • 53
  • Does this answer your question? [List changes unexpectedly after assignment. Why is this and how can I prevent it?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it) – Thomas Weller Mar 04 '22 at 12:02

1 Answers1

2

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

  • 2
    `r2` is a new `ndarray` object, but is a `view`. So yes you want a copy, but it doesn't need to a deep copy (that's more applicable to lists). – hpaulj Dec 27 '18 at 04:44