Why is np.where's result read-only for multi-dimensional arrays?

numpy, python

Solution

Internally numpy computes results in a one dimensional array, but then returns a tuple which are views with same stride on this array, one for each dimension;

for example, if the array is like this:

>>> a
array([[0, 1, 0],
       [3, 0, 5]])

internally numpy first calculates

>>> i
array([0, 1, 1, 0, 1, 2])

where `i[2 * k]` and `i[2 * k + 1]` are the indices of the `k`'th non-zero value; but, then the result that is returned is:

>>> (i[::2], i[1::2])
(array([0, 1, 1]), array([1, 0, 2]))

when, it creates the view it passes `0` as the `flags` argument. So, the writable flag is unset.

When the input array is one dimensional, it takes a short-cut and therefore the flags are set differently.

Problem

``` >>> a = np.where(np.ones(5))[0] >>> a array([0, 1, 2, 3, 4]) >>> a.flags['WRITEABLE'] True >>> b = np.where(np.ones((5,2)))[0] >>> b array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4]) >>> b.flags['WRITEABLE'] False ``` Why is `b` read-only while `a` is not? This is not mentioned in the documentation.

Original source