Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Are numpy arrays linked when one array is transposed?

Currently I am working on a python script which extracts measurement data from a text file. I am working with iPython Notebook and Python 2.7

Now I experienced some odd behaviour when working with numpy arrays. I have no explanation for this.

myArray = numpy.zeros((4,3))
myArrayTransposed = myArray.transpose()

for i in range(0,4):
    for j in range(0,3):
        myArray[i][j] = i+j

print myArray
print myArrayTransposed

leads to:

[[ 0.  1.  2.]
 [ 1.  2.  3.]
 [ 2.  3.  4.]
 [ 3.  4.  5.]]
 [[ 0.  1.  2.  3.]
 [ 1.  2.  3.  4.]
 [ 2.  3.  4.  5.]]

So without working on the transposed array, values are updated in this array.

How is this possible?

like image 724
engineController Avatar asked Sep 26 '22 14:09

engineController


1 Answers

From http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html:

Different ndarrays can share the same data, so that changes made in one ndarray may be visible in another. That is, an ndarray can be a “view” to another ndarray, and the data it is referring to is taken care of by the “base” ndarray. ndarrays can also be views to memory owned by Python strings or objects implementing the buffer or array interfaces.

When you do a transpose(), this returns a "view" to the original ndarray. It points to the same memory buffer, but it has a different indexing scheme:

A segment of memory is inherently 1-dimensional, and there are many different schemes for arranging the items of an N-dimensional array in a 1-dimensional block. Numpy is flexible, and ndarray objects can accommodate any strided indexing scheme.

To create an independent ndarray, you can use numpy.array() operator:

myArrayTransposed = myArray.transpose().copy()
like image 74
Adi Levin Avatar answered Sep 28 '22 23:09

Adi Levin