[Numpy-discussion] Python scalar float indices into array work - but not for array indices - why ?

Robert Kern robert.kern at gmail.com
Wed Nov 17 14:40:15 EST 2010


On Wed, Nov 17, 2010 at 13:27, Sebastian Haase <seb.haase at gmail.com> wrote:

> I guess you are right again - see this simplified 1d test:
>>>> a = np.zeros(4, int)
>>>> a
> [0 0 0 0]
>>>> a[ [1,3] ] += 1
>>>> a
> [0 1 0 1]
>>>> a[ [1,3,1] ] += 1
>>>> a
> [0 2 0 2]
>>>>
>>>> a = np.zeros(4, int)
>>>> a
> [0 0 0 0]
>>>> a[ [np.array((1,3))] ] += 1
>>>> a
> [0 1 0 1]
>>>> a[ [np.array((1,3,1))] ] += 1
>>>> a
> [0 2 0 2]
>
> So, the fancy indexing appears to treat arrays exactly like plain lists.
> And my idea of using it for operating on a sequence of indices appears
> to work at first,
> but then in case of duplicate indices (1 in my example) the += works
> only once ....
> I don't understand ...

As we've discussed several times before on this list, "foo[i] += 1" is
not an atomic operation. It breaks down into the equivalent code:

  tmp = foo.__getitem__(i)
  tmp = tmp.__iadd__(1)
  foo.__setitem__(i, tmp)

In the case of fancy indexing, tmp is not a view on foo. Each of the
duplicate indices makes a copy of the data. Those copies are
incremented independently, then they are shoved back into the original
foo array. At no point does the array know that these methods are
being called because of this special combination of operators and that
you want it to behave like a histogram.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the NumPy-Discussion mailing list