0

When i am trying to create a numpy array and i tired manipulating it using splicing .ideals spliced array and original array should remain same but it is not .Why?

a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

i have taken this array i will splice now and update its value

c = a[:2,1:3]
c[0,0] = 99 

now the value of a also gets updated at its respective position in python this happens only when the address is same

when i am checking id of each it shows different

print(id(c),id(a))

output :

139866833241552 139866835761152
BoarGules
  • 16,440
  • 2
  • 27
  • 44
Cherry
  • 1
  • `c` is a `view` of `a`. It is a different object, hance the djfferent `id`. `id` tells us nothing about shaped data-buffer (bass). Don't skip the 'numpy for beginners' intro docs. – hpaulj Jul 08 '21 at 00:50
  • I just commented on another use of `id`, here: https://stackoverflow.com/questions/68285640/how-numpy-arrays-are-stored-in-memory-locations – hpaulj Jul 08 '21 at 01:56

1 Answers1

0
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  9, 10, 11]])
>>> c=a[:2,1:3]
>>> c
array([[2, 3],
       [7, 9]])
>>> c[0,0]
2
>>> c[0,0]=99
>>> c
array([[99,  3],
       [ 7,  9]])
>>> a
array([[ 1, 99,  3,  4,  5],
       [ 6,  7,  9, 10, 11]])

Your question is why is a reflecting changes in c?

  1. Because c and a are pointing to the same object
  2. To make a copy of a, you create a new object

as below-

>>> a
array([[ 1, 99,  3,  4,  5],
       [ 6,  7,  9, 10, 11]])
>>> c=np.array(a)
>>> c
array([[ 1, 99,  3,  4,  5],
       [ 6,  7,  9, 10, 11]])
>>> c[0,0]=100
>>> c
array([[100,  99,   3,   4,   5],
       [  6,   7,   9,  10,  11]])
>>> a
array([[ 1, 99,  3,  4,  5],
       [ 6,  7,  9, 10, 11]])````
  • `c` is a different array object, with its own shape. But it is a `view`. That's an important concept in numpy. – hpaulj Jul 08 '21 at 00:54