Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does NumPy array not update original array using predictor

I am learning NumPy (and Python) and working through some exercises regarding arrays. I had a question that came up that I could not comprehend. I understand that the following code should update the original array that b is pointed to. The code is as follows.

a = np.zeros((4,5))
b = a[1:3,0:3]
b = b + 100
print('a = ', a)
print('b = ', b)

The output is:

a =  [[0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0.]]
b =  [[100. 100. 100.]
 [100. 100. 100.]]

Why does a not update along with b? I understand that a pointer object should update the original with edits. I'm assuming it is due to the syntax that 100 is added to b. The code below updates, as I thought, with the original array changing. What is the difference?

a = np.zeros((4,5))
b = a[1:3,0:3]
b[0, 0] = 100
print('a = ', a)

Output:

a =  [[  0.   0.   0.   0.   0.]
 [100.   0.   0.   0.   0.]
 [  0.   0.   0.   0.   0.]
 [  0.   0.   0.   0.   0.]]
like image 713
dankest_graph Avatar asked Sep 19 '26 15:09

dankest_graph


1 Answers

Python does not have pointers, at least not in the sense of other languages such as C.

What is happening here is that when you index an array, i.e. a[1:3,0:3], you create a view of a part of the data in a. Numpy docs on what views are

In your first example, you then evaluate b + 100, which creates a new array. This behavior is not changed by the fact that you assign the result to the same variable name b.

In your second example b[0, 0] = 100, you modify b in-place. Since b is just a view of a, you also modify corresponding entries of a.

You could rewrite your first example to do b += 100 instead, which again modifies b in-place and will also change a

like image 140
Jakob Unfried Avatar answered Sep 21 '26 04:09

Jakob Unfried



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!