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


the example

the documentation assigning value indexed arrays shows example unexpected results 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 naively expect value of array @ x[1]+1 being incremented 3 times, instead assigned x[1] 3 times.

the problem

what confuse me expecting operation x += 1 behave in normal python, x = x + 1, x resulting array([11, 11, 31, 11]). in 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 happening in original example? can 1 elaborate more explanation?

second:

it documented behavior, i'm ok that. think should behave described because expected pythonistic point of view. so, because want convinced: there reason behave on "my expected" behavior?

the problem second example give not same first. it's easier understand if @ value of x[np.array([1, 1, 3, 1])] + 1 separately, numpy calculates in both examples.

the value of x[np.array([1, 1, 3, 1])] + 1 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, assign answer elements 1 , 3 in original array x. means new value 11 assigned element 1 3 times.

however, in example 2, replace original array x new array array([11, 11, 31, 11]).

this correct equivalent code first example, , gives 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]) 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -