python - Apparently inconsistent reference behavior in NumPy -


when referencing given row 1 in 2d numpy array, noticed me looks unexpected behavior

a = np.array([[1,2], [3, 4]]) a[1] = a[0] a[1] += 100 

after operation, a equal to:

array([[  1,   2], [101, 102]]) 

i not understand why reference a[0] not considered , a[1] modified. because python lists not case:

a = [[1,2], [3,4]] a[1] = a[0] a[1][1] = 999 

this give a:

[[1, 999], [1, 999]] 

a numpy array of not-object dtype not contain references. when set a[1] = a[0] copies content of a[0] a[1]. means subsequent assignments a[1] or a[0] won't change other one.

a list on other hand doesn't copy when have a[1] = a[0] inserts reference a[0] in a[1]. means assignment either a[1] or a[0] change other one.

the take-away probably: don't think of numpy array containing references. it's not nested "array" if multidimensional. it's one-dimensional array uses "strides" "appear multidimensional".


it may compare "identities" here. that's bit more complicated because numpy doesn't work references works memory buffer. numpy provides function check shared memory:

>>> import numpy np >>> = np.array([[1,2], [3, 4]]) >>> a[1] = a[0] >>> np.shares_memory(a[1], a[0])  # arrays don't share memory false  >>> = [[1,2], [3,4]] >>> a[1] = a[0] >>> a[1] a[0]                  # same object true 

note different if take "view" of numpy array without assigning array. assignment numpy array copy. that's because, said, numpy arrays don't store references, stores elements. can have view array can't insert view as view numpy array.

for example:

>>> = np.array([[1,2], [3, 4]]) >>> b = a[0]                      # b view "a" >>> np.shares_memory(b, a[0]) true  >>> a[1] = b >>> np.shares_memory(b, a[1])     # a[1] not view "a[0]". false 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -