1
img_1 = np.arange(25).reshape(5,5)

img_2 = img_1

locs = np.where(img_2 >= 0)

img_2[locs]  = [65000]

Wondering is there an way to have img_1 with initial array and only img_2 will will be modified?

Both img_1 and img_2 array is changing.

toyota Supra
  • 3,181
  • 4
  • 15
  • 19
MH_AU
  • 11
  • 3
  • You can use `img2 = img1.copy()`. `img2 = img1` makes `img2` point to the same data as `img1`. – B Remmelzwaal Feb 07 '23 at 02:09
  • This isn't unique to numpy arrays. `img2 = img1` will make `img2` reference the exact same object as `img1`, regardless of what `img1` is. For more on this, see [what does it mean by 'passed by assignment'?](https://stackoverflow.com/q/50534394/11082165) – Brian61354270 Feb 07 '23 at 02:14
  • for a numpy array or a pandas dataframe.. ```img2=img1.copy()``` will give you a copy .. for other objects which donot have a copy() method inplemented ... `import copy` and `obj2=copy.deepcopy(obj1)` will give you true copy and not a reference – geekay Feb 07 '23 at 02:34
  • In addition, there's also a shorter way to do the operation you did the code. ```img_2[img_2>=0]``` produces the same result. The argument produces a Boolean for each element of img_2, i.e., accordingly the array img_2 takes the values. – Pixel_Bear Feb 07 '23 at 04:14

1 Answers1

1

All you need is just the np.where() alone. Do like this.

import numpy as np

img_1 = np.arange(25).reshape(5,5)
img_2 = np.where(img_1 >= 0, 65000, img_1)
relent95
  • 3,703
  • 1
  • 14
  • 17