6

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?

3
  • 1
    transpose does not create a copy. It just changes the order the same data is read into. Would be strange if the numpy docs did not mention this Commented Jan 22, 2016 at 11:22
  • 1
    They indeed mention it here. The return valur is a "View" to the original array Commented Jan 22, 2016 at 11:24
  • 1
    myArray.T.copy() if you want a true copy. .T is shorthand for .transpose() Commented Jan 22, 2016 at 11:27

1 Answer 1

4

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()
Sign up to request clarification or add additional context in comments.

3 Comments

Hello and thanks to all who have answered my questions. You gave me valuable hints. Have a nice day!
Maybe the numpy.copy function would be more explicit to achieve what the OP wants: myArrayTransposed = myArray.transpose().copy()
Yes. I agree. Fixed it :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.