Why does incrementing an indexed array behave as described in numpy's user documentation?

Example

The documentation on assigning a value to indexed arrays shows an example with unexpected results for these naive programmers.

>>> x = np.arange(0, 50, 10) >>> x array([ 0, 10, 20, 30, 40]) >>> x[np.array([1, 1, 3, 1])] += 1 >>> x array([ 0, 11, 20, 31, 40]) 

The documentation says that people can naively expect the value of the array at x[1]+1 to increase three times, but instead it is assigned x[1] three times.

Problem

What really bothers me is that I expected the operation x += 1 behave the same way as in normal Python, like x = x + 1 , so x turns out to be array([11, 11, 31, 11]) Like in this example:

 >>> x = np.arange(0, 50, 10) >>> x array([ 0, 10, 20, 30, 40]) >>> x = x[np.array([1, 1, 3, 1])] + 1 >>> x array([11, 11, 31, 11]) 

Question

First of all:

What happens in the original example? can anyone explain this in more detail?

Secondly:

This is documented behavior, I'm fine with that. But I think that it should behave as I described, because it is what is expected from the point of view of Pythonistic. So, simply because I want to be sure: is there a good reason why it behaves as if it was due to β€œmy expected” behavior?

+4
source share
1 answer

The problem is that the second example you give does not match the first. This is easier to understand if you look at the value of x[np.array([1, 1, 3, 1])] + 1 separately, which numpy computes in both examples.

The value of x[np.array([1, 1, 3, 1])] + 1 is what you expected: array([11, 11, 31, 11]) .

 >>> x = np.arange(0, 50, 10) >>> x array([ 0, 10, 20, 30, 40]) >>> x[np.array([1, 1, 3, 1])] + 1 array([11, 11, 31, 11]) 

In Example 1, you assign this answer to elements 1 and 3 in the original x array. This means that a new value of 11 is assigned to element 1 three times.

However, in Example 2, you replace the original array x with the new array([11, 11, 31, 11]) .

This is the correct equivalent code for your first example and gives the same result.

 >>> x = np.arange(0, 50, 10) >>> x array([ 0, 10, 20, 30, 40]) >>> x[np.array([1, 1, 3, 1])] = x[np.array([1, 1, 3, 1])] + 1 >>> x array([ 0, 11, 20, 31, 40]) 
+7
source

Source: https://habr.com/ru/post/1491924/


All Articles