numpy.diagonal returning read-only copy even in version 1.10

Asked

Viewed 120 times

6

I’m doing a program in Python where I need to change the values diagonally from an array. The following chunk of code should be sufficient to understand the general idea (it changes to 2 the value at the first position of the main diagonal of the matrix):

import numpy as np
x = np.eye(2)
d = x.diagonal()
d[0] = 2

According to the documentation, in version 1.9 the return of this function had become read-only, but this was undone in version 1.10 (which supposedly returns a reference to the original matrix):

In versions of Numpy prior to 1.7, this Function Always returned a new, Independent array containing a copy of the values in the diagonal.

In Numpy 1.7 and 1.8, it continues to Return a copy of the diagonal, but Depending on this Fact is deprecated. Writing to the Resulting array continues to work as it used to, but a Futurewarning is issued.

In Numpy 1.9 it Returns a read-only view on the original array. Attempting to write to the Resulting array will Produce an error.

In Numpy 1.10, it will Return a read/write view and writing to the returned array will alter your original array. The returned array will have the same type as the input array.

Well, I had version 1.9 installed here (Windows 8) but I just upgraded it (using pip install -upgrade numpy). Guaranteed the current version is correct:

>>> np.version.version
'1.10.1'

However, even so, the example code above generates the following error:

>>> import numpy as np
>>> x = np.eye(2)
>>> d = x.diagonal()
>>> d[0] = 2
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    d[0] = 2
ValueError: assignment destination is read-only

There is a whole discussion about the changes in the versions in this thread - just where I picked up the minimum example previously presented - but I did not find any information that contradicts the documentation.

Can someone offer some help?

1 answer

2


So what happens is, as you’ve seen, there’s a very big discussion about what this function should come back to, there being a lot of divergent opinions.

If you follow the Issue regarding this you will see that it was marked as a task for version 1.11.

But to clarify this behavior, just look at the code: in the version 1.10.1 she still does the same thing as in the version 1.9.3, that is, the writeable flag continues to be removed from the array at the end of the function.

In the method documentation, it says that it will have the new (or old) behavior still in 1.10, implying that this can still happen in minor releases. But as it was scheduled as a task for 1.11, I believe you will have to wait a little longer (but this is just my speculation).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.