Code: Select all

` i = np.array( [1,5,2,6,4,3,6,7,4,3,2] `

Code: Select all

` v = np.array( [2,5,2,3,4,1,2,1,6,4,2] `

Code: Select all

` d = np.zeros( 10) `

Code: Select all

```
for index, worth in enumerate( v):.
idx = i [index] d [idx] = v [index]
```

I have unsorted range of indexes: I likewise have a range of worths of the very same length: I have variety with zeros of wanted worths: Now I want to add to aspects in d values of v based on it's index in i. If I do it in plain python I would do it like this: It is ugly and inefficient. How can I change it?

Code: Select all

` i = np.array( [1,5,2,6,4,3,6,7,4,3,2] `

Code: Select all

` v = np.array( [2,5,2,3,4,1,2,1,6,4,2] `

Code: Select all

` d = np.zeros( 10) `

Code: Select all

```
for index, worth in enumerate( v):.
idx = i [index] d [idx] = v [index]
```

Code: Select all

` np.bincount `

Code: Select all

```
counts = np.bincount( i, v).
d [: counts.size] = counts
```

Code: Select all

` np.add.at `

Code: Select all

` other post `

Code: Select all

` np.bincount `

Code: Select all

```
In [61]: def bincount_based( d, i, v):.
...: counts = np.bincount( i, v).
...: d [: counts.size] = counts.
...:.
...: def add_at_based( d, i, v):.
...: np.add.at( d, i, v).
...:.
In [62]: # Inputs (random numbers).
...: N = 10000.
...: i = np.random.randint( 0,1000,( N)).
...: v = np.random.randint( 0,1000,( N)).
...:.
...: # Setup output varieties for two methods.
...: M = 12000.
...: d1 = np.zeros( M).
...: d2 = np.zeros( M).
...:.
In [63]: bincount_based( d1, i, v) # Run approaches.
...: add_at_based( d2, i, v).
...:.
In [64]: np.allclose( d1, d2) # Validate outputs.
Out [64]: True.
In [67]: # Setup output arrays for two approaches once again for timing.
...: M = 12000.
...: d1 = np.zeros( M).
...: d2 = np.zeros( M).
...:.
In [68]: %timeit add_at_based( d2, i, v).
1000 loops, finest of 3: 1.83 ms per loop.
In [69]: %timeit bincount_based( d1, i, v).
10000 loops, best of 3: 52.7 s per loop
```