2

sorry this question came up before here Setting two arrays equal But the solution did not work and i dont know why.

import numpy as np

zero_matrix = np.zeros((3,3)) # 3x3 zero matrix

test_matrix = zero_matrix[:] # test_matrix is a view of zero_matrix. Without [:] it would be same object
print (zero_matrix)
print ()
print (test_matrix)
print ()
print(id(test_matrix))
print ()
print(id(zero_matrix))
print ()

test_matrix[1] = 42

print (test_matrix)
print ()
print (zero_matrix)

the 'zero_matrix' is also changed when i set the test_matrix[1] = 42.

And i dont get why since both have different object ids.

David
  • 35
  • 4

3 Answers3

1

Use copy to copy your numpy arrays:

zero_matrix = np.zeros((3,3))
test_matrix = zero_matrix.copy()
test_matrix[1] = 42
print(zero_matrix)
print(test_matrix)

Numpy arrays and python lists behave differently in this regard.

tfeldmann
  • 3,108
  • 1
  • 23
  • 34
1

They indeed have both different object IDs, but, as you write yourself: test_matrix is a view of zero_matrix.

An object is usually called a "view object" when it provides a way to access another object (be it by reading or by writing). In this case, accesses to this view object are deflected to the other object both by reading and writing.

That's a speciality of numpy objects opposed to "normal" python objects.

But even python has these objects, but doesn't use them unless explicitly requested.

glglgl
  • 89,107
  • 13
  • 149
  • 217
1

This is what is mean by the comment in your code that says test_matrix is a "view". A view does not have its own copy of the data. Rather it shares the underlying data of the original array. Views do not have to be of the entire array, but can be of small sub-sections of the array. These sub sections do not even need to be contiguous if the view is strided. eg.

a = np.arange(10)
b = a[::2] # create a view of every other element starting with the 0-th
assert list(b) == [0, 2, 4, 6, 8]
assert a[4] == 4
b[2] = -1
assert a[4] == -1

Views are powerful as they allow more complex operations without having to copy large amounts of data. Not needing to copy data all the time can mean some operations are faster than they otherwise would be.

Beware, not all index operations create views. eg.

a = np.arange(10, 20)
b = a[[1,2,5]]
assert list(b) == [11, 12, 15]
b[0] == -1
assert a[1] != -1
Dunes
  • 37,291
  • 7
  • 81
  • 97