Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why increment an indexed array behave as documented in numpy user documentation?

The example

The documentation about assigning value to indexed arrays shows an example with unexpected results for those 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 people could naively expect the value of the array at x[1]+1 being incremented three times, but instead it is assigned to x[1] three times.

The Problem

What really confuse me is that what i was expecting was the operation x += 1 behave like it does in normal Python, as x = x + 1, so x resulting array([11, 11, 31, 11]). As 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])

The Question

First:

What is happening in the original example? can some one elaborate more the explanation?

Second:

It is a documented behavior, i'm Ok with that. But i think it should behave as i described because is what is expected from a Pythonistic point of view. So, just because i want to be convinced: is there a good reason it behave like it does over "my expected" behavior?

like image 949
jgomo3 Avatar asked Mar 24 '23 03:03

jgomo3


1 Answers

The problem is the second example you give is not the same as the first. It's easier to understand if you look at the value of x[np.array([1, 1, 3, 1])] + 1 separately, which numpy calculates in both your examples.

The value of x[np.array([1, 1, 3, 1])] + 1 is what you had 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 array x. This means the new value 11 is assigned to element 1 three times.

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

This is the correct equivalent code to 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])
like image 160
ijmarshall Avatar answered Apr 06 '23 23:04

ijmarshall