[Numpy-discussion] Array indexing and repeated indices

Nicolas Rougier Nicolas.Rougier at inria.fr
Fri Mar 1 02:30:52 EST 2013


Hi,

I'm trying to increment an array using indexing and a second array for increment values (since it might be a little tedious to explain, see below for a short example). 

Using "direct" indexing, the values in the example are incremented by 1 only while I want to achieve the alternative behavior. My question is whether there is such function in numpy or if there a re better way to achieve the same result ?
(I would like to avoid the while statement)

I found and adapted the alternative solution from: http://stackoverflow.com/questions/2004364/increment-numpy-array-with-repeated-indices but it is only for a fixed increment from what I've understood.


Nicolas


# ------------------------

import numpy as np

n,p = 5,100
nodes = np.zeros( n, [('value', 'f4', 1)] )
links = np.zeros( p, [('source', 'i4', 1),
                      ('target', 'i4', 1)])
links['source'] = np.random.randint(0, n, p)
links['target'] = np.random.randint(0, n, p)

targets = links['target'] # Indices can be repeated
K = np.ones(len(targets)) # Note K could be anything

# Direct indexing
nodes['value'] = 0
nodes['value'][targets] += K
print nodes

# "Alternative" indexing
nodes['value'] = 0
B = np.bincount(targets)
while B.any():
    I = np.argwhere(B>=1)
    nodes['value'][I] += K[I]
    B = np.maximum(B-1,0)
print nodes




More information about the NumPy-Discussion mailing list