[Numpy-discussion] Easy way to vectorize a loop?
Mon Mar 2 11:23:07 CST 2009
On Mon, Mar 2, 2009 at 09:34, Ravi <email@example.com> wrote:
> On Monday 02 March 2009 01:58:27 Robert Kern wrote:
>> > for i in range(len(vals)):
>> > flattened[idx[i]]+=vals[i]
>> flattened[idx] = vals
> Assuming 'idx' and 'vals' are one-dimensional arrays, that should be
> flattened[ idx[:numpy.size(vals)] ] += vals
> flattened[ idx ] += vals
> if 'vals' and 'idx' have the same size.
Oops. I missed the +. Actually, neither of these will work when idx
has repeated indices. Instead, use:
flattened += np.bincount(idx, vals)
"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
-- Umberto Eco
More information about the Numpy-discussion