Why does NumPy array not update original array using predictor

Question:

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.]]
Asked By: dankest_graph

||

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

Answered By: Jakob Unfried

In the first code block, you are setting the value of b equal to what it was before + and adding 100 to all of its value.

b = b + 100

In the second code block, you are setting the value of the number in the [0, 0] position equal to 100. Since b is just a pointer to a, it also modifies the value of a

b[0, 0] = 100

The difference between the two is that in the first one you are cloning b then modify it (then assign it to b). Where in the second one, you do not clone it, and just modifies it.

Answered By: Wutong
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.