[Numpy-discussion] Array indexing and repeated indices

Sebastian Berg sebastian@sipsolutions....
Fri Mar 1 04:04:07 CST 2013


On Fri, 2013-03-01 at 08:30 +0100, Nicolas Rougier wrote:
> 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)

bincount takes a weights argument which should do exactly what you are
looking for.

- Sebastian

> while B.any():
>     I = np.argwhere(B>=1)
>     nodes['value'][I] += K[I]
>     B = np.maximum(B-1,0)
> print nodes
> 
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
> 




More information about the NumPy-Discussion mailing list