[SciPy-user] fancy indexing and +=

A. M. Archibald peridot.faceted at gmail.com
Fri Sep 1 16:27:51 CDT 2006


Hi,

I'm trying to figure out how to use fancy indexing for ordinary
(non-sparse) arrays. On reading, it's clear enough what is meant:

a = arange(3)
a[[1,1,2]]
-> array([1,1,2])

But when writing it's not so clear what should happen:

a[[1,1,2]] = array([1,2,3])
a
-> array([0,2,3])

All right, the assignment a[1]=... has been done twice, so I only see
the effects of the second. Fair enough. But:

a[[1,1,2]] += 1
a
-> array([0,3,4])

That is, a[[1,1,2]] += 1 is equivalent to

a[[1,1,2]] = a[[1,1,2]] + 1

and not

for i in [1,1,2]:
    a[i]+=1

Is this really intended? It's surprising, it seems like that forces
numpy to make a copy, and it leaves me with the question of how to
implement the second without a loop... Well, for a better example:

x = array([...])
i1 = ravel(ix_(arange(len(x)),arange(len(x)))[...,0])
i2 = ravel(ix_(arange(len(x)),arange(len(x)))[...,1])

dx = f(x[i1],x[i2]) # compute all the pairwise interactions

# x[i1] += dx
for (i,a) in enumerate(i1):
    x[a]+=dx[i]

How do I write something like this without a loop? Sort i1 and concoct
something that adds all the values with the same index before adding
it to x?

Thanks,
A. M. Archibald


More information about the SciPy-user mailing list