[Numpy-discussion] nicest way to apply an arbitrary sequence of row deltas to an array
Pauli Virtanen
pav+sp@iki...
Mon Dec 21 05:35:45 CST 2009
Mon, 21 Dec 2009 09:35:08 +0000, Neil wrote:
[clip]
> I'm also interested to see if there are any answers to this; I came
> across a similar problem recently. It would have been convenient to do
> something like U[idx] += dU, but this didn't work because there were
> repeated indices in idx. Here's a short example that shows the problem:
>
> In [1]: U = np.array([1., 2., 3., 4.])
> In [2]: dU = np.array([0.1, 0.1, 0.1, 0.1])
> In [3]: idx = np.array([0, 1, 2, 0])
> In [4]: U
> Out[4]: array([ 1., 2., 3., 4.])
> In [5]: U[idx]
> Out[5]: array([ 1., 2., 3., 1.])
> In [6]: U[idx] += dU
> In [7]: U
> Out[7]: array([ 1.1, 2.1, 3.1, 4. ])
>
> Ideally U would end up as array([ 1.2, 2.1, 3.1, 4. ])
One solution could be to use bincount:
d = np.bincount(idx, dU)
U[:len(d)] += d
Also, bincount works only with scalar weights, so this is not a fully
vectorized solution.
A dedicated function could be nice here.
--
Pauli Virtanen
More information about the NumPy-Discussion
mailing list