[SciPy-User] MATLAB accumarray equivalent ?
Alan G Isaac
aisaac at american.edu
Fri Mar 26 11:25:57 EDT 2010
On 3/26/2010 10:39 AM, Mohammad Abdollahi wrote:
> Does anyone know what is the equivalent function of MATLAB's
> "accumarray()" in scipy/numpy, with the exact same functionality ?
That certainly gets the basic accumarray functionality:
>>> vals = 101+np.arange(5)
>>> subs = np.array([1,2,4,2,4])-1
>>> np.bincount(subs,vals)
array([ 101., 206., 0., 208.])
Here's another way that maybe easier
to adapt to whatever the OP needs:
>>> from collections import defaultdict
>>> d = defaultdict(float)
>>> for i, cat in enumerate(subs):
... d[cat] += vals[i]
...
>>> d
defaultdict(<type 'float'>, {0: 101.0, 1: 206.0, 3: 208.0})
That should actually be pretty fast,
though not as fast as bincount of course.
What's the use case?
hth,
Alan Isaac
More information about the SciPy-User
mailing list