Use np.bincount with the weights optional argument. In your example you would do:

np.bincount(accmap, weights=a)
Answer from Jaime on Stack Overflow
Top answer
1 of 7
22

Use np.bincount with the weights optional argument. In your example you would do:

np.bincount(accmap, weights=a)
2 of 7
10

Late to the party, but...

As @Jamie says, for the case of summing, np.bincount is fast and simple. However in the more general case, for other ufuncs such as maximum, you can use the np.ufunc.at method.

I've put together a gist[see link below instead] which encapsulates this in a Matlab-like interface. It also takes advantage of the repeated indexing rules to provide a 'last' and 'first' function, and unlike Matlab, 'mean' is sensibly optimized (calling accumarray with @mean in Matlab is really slow because it runs a non-builtin function for every single group, which is stupid).

Be warned that I haven't particularly tested the gist, but will hopefully update it in future with extra features and bugfixes.

Update May/June-2015: I have reworked my implementation - it is now available as part of ml31415/numpy-groupies and available on PyPi (pip install numpy-groupies). Benchmarks are as follows (see github repo for up-to-date values)...

function  pure-py  np-grouploop   np-ufuncat np-optimised    pandas        ratio
     std  1737.8ms       171.8ms     no-impl       7.0ms    no-impl   247.1: 24.4:  -  : 1.0 :  -  
     all  1280.8ms        62.2ms      41.8ms       6.6ms    550.7ms   193.5: 9.4 : 6.3 : 1.0 : 83.2
     min  1358.7ms        59.6ms      42.6ms      42.7ms     24.5ms    55.4: 2.4 : 1.7 : 1.7 : 1.0 
     max  1538.3ms        55.9ms      38.8ms      37.5ms     18.8ms    81.9: 3.0 : 2.1 : 2.0 : 1.0 
     sum  1532.8ms        62.6ms      40.6ms       1.9ms     20.4ms   808.5: 33.0: 21.4: 1.0 : 10.7
     var  1756.8ms       146.2ms     no-impl       6.3ms    no-impl   279.1: 23.2:  -  : 1.0 :  -  
    prod  1448.8ms        55.2ms      39.9ms      38.7ms     20.2ms    71.7: 2.7 : 2.0 : 1.9 : 1.0 
     any  1399.5ms        69.1ms      41.1ms       5.7ms    558.8ms   246.2: 12.2: 7.2 : 1.0 : 98.3
    mean  1321.3ms        88.3ms     no-impl       4.0ms     20.9ms   327.6: 21.9:  -  : 1.0 : 5.2 
Python 2.7.9, Numpy 1.9.2, Win7 Core i7.

Here we are using 100,000 indices uniformly picked from [0, 1000). Specifically, about 25% of the values are 0 (for use with bool operations), the remainder are uniformly distribuited on [-50,25). Timings are shown for 10 repeats.

  • purepy - uses nothing but pure python, relying partly on itertools.groupby.
  • np-grouploop - uses numpy to sort values based on idx, then uses split to create separate arrays, and then loops over these arrays, running the relevant numpy function for each array.
  • np-ufuncat - uses the numpy ufunc.at method, which is slower than it ought to be - as disuccsed in an issue I created on numpy's github repo.
  • np-optimisied - uses custom numpy indexing/other tricks to beat the above two implementations (except for min max prod which rely on ufunc.at).
  • pandas - pd.DataFrame({'idx':idx, 'vals':vals}).groupby('idx').sum() etc.

Note that some of the no-impls may be unwarranted, but I haven't bothered to get them working yet.

As explained on github, accumarray now supports nan-prefixed functions (e.g. nansum) as well as, sort, rsort, and array. It also works with multidimensional indexing.

🌐
Stack Overflow
stackoverflow.com › questions › 72271614 › translate-accumarray-matlab-to-python
numpy - Translate accumarray (Matlab) to python - Stack Overflow
May 17, 2022 - >>> accum(accmap, a, func=lambda x: x, dtype='O') array([[[1, 2, 4, -1], [3, 6]], [[-1, 8], [9]]], dtype=object) """ # Check for bad arguments and handle the defaults. if accmap.shape[:a.ndim] != a.shape: raise ValueError("The initial dimensions of accmap must be the same as a.shape") if func is None: func = np.sum if dtype is None: dtype = a.dtype if accmap.shape == a.shape: accmap = np.expand_dims(accmap, -1) adims = tuple(range(a.ndim)) if size is None: size = 1 + np.squeeze(np.apply_over_axes(np.max, accmap, axes=adims)) size = np.atleast_1d(size) # Create an array of python lists of values.
Discussions

pandas - Python transcription of Matlab's accumarray - Stack Overflow
I would like to get the same result as Matlab's accumarray function in Python. I know that there are some other discussions which provide solutions to this problem but the case I consider seems to be More on stackoverflow.com
🌐 stackoverflow.com
What does accumarray([1,2,3], 1) do?
What exactly are you trying to do? Typically, the first input arg is a column vector and you get a group count, as you already know. If you pass a matrix in the first input arg, you are asking it to shape the output in a different ways. In this case, by passing [1,2,3] , you are asking it to return the result in 1x2x3 3D matrix. Why on earth anyone wants it I have no idea, but you can do it if you want to. More on reddit.com
🌐 r/matlab
1
2
September 12, 2022
Newest 'accumarray' Questions - Stack Overflow
I recently try to transfer some function from matlab to python. A function in matlab called "accumarray", accumarray(3d_array(10*10*10),1), the output is also 101010 3d array. More on stackoverflow.com
🌐 stackoverflow.com
Analogue to accumarray (matlab) - sparse pooling
Hi, I’m wondering if there’s a way to emulate the behavior of accumarray in Matlab. More specifically, my use case is to project 2D image features to the ground-plane as it has been done in MapNet. The exact specifications are as follows: Inputs: feat - image features with size (B, F, H, ... More on discuss.pytorch.org
🌐 discuss.pytorch.org
0
0
February 21, 2019
🌐
Readthedocs
scipy-cookbook.readthedocs.io › items › AccumarrayLike.html
accumarray like function — SciPy Cookbook documentation
March 31, 2010 - from itertools import product import numpy as np def accum(accmap, a, func=None, size=None, fill_value=0, dtype=None): """ An accumulation function similar to Matlab's `accumarray` function. Parameters ---------- accmap : ndarray This is the "accumulation map".
🌐
Stack Overflow
stackoverflow.com › questions › 55855573 › python-transcription-of-matlabs-accumarray
pandas - Python transcription of Matlab's accumarray - Stack Overflow
It handels a couple of things the Matlab function does. Copydef accumarray(subs, vals, size=None, fun=np.sum): if len(subs.shape) == 1: if size is None: size = [subs.values.max() + 1, 0] acc = val.groupby(subs).agg(fun) else: if size is None: size = [subs.values.max()+1, subs.shape[1]] subs = subs.copy().reset_index() by = subs.columns.tolist()[1:] acc = subs.groupby(by=by)['index'].agg(list).apply(lambda x: val[x].agg(fun)) acc = acc.to_frame().reset_index().pivot_table(index=0, columns=1, aggfunc='first') acc.columns = range(acc.shape[1]) acc = acc.reindex(range(size[1]), axis=1).fillna(0) id_x = range(size[0]) acc = acc.reindex(id_x).fillna(0) return acc
🌐
MathWorks
mathworks.com › matlab › data import and analysis › data preprocessing
accumarray - Accumulate vector elements - MATLAB
This MATLAB function sums groups of data by accumulating elements of a vector data according to the groups specified in ind.
🌐
SciPy
scipy.github.io › old-wiki › pages › Cookbook › AccumarrayLike.html
accum, a function like MATLAB's accumarray
1 from itertools import product 2 import numpy as np 3 4 5 def accum(accmap, a, func=None, size=None, fill_value=0, dtype=None): 6 """ 7 An accumulation function similar to Matlab's `accumarray` function. 8 9 Parameters 10 ---------- 11 accmap : ndarray 12 This is the "accumulation map".
🌐
GitHub
gist.github.com › d1manson › 5f78561c0f52d3073fe8
[!!!SUPERSEDED BY ACTUAL REPOSITORY - https://github.com/ml31415/accumarray !!!] Matlab-like accumarray in Python · GitHub
[!!!SUPERSEDED BY ACTUAL REPOSITORY - https://github.com/ml31415/accumarray !!!] Matlab-like accumarray in Python - accumarray.py
🌐
GitHub
github.com › ml31415 › numpy-groupies › issues › 23
Equivalence between accumarray and aggregate? · Issue #23 · ml31415/numpy-groupies
April 25, 2019 - I need to translate in Python the following Matlab instruction coming from here: binned_data = accumarray(bins(all(bins>0,2),:),1/nrows,M(ones(1,ncols))); I tried to replace it with binned_data = aggregate( bins[ all(bins > 0, 1), : ], 1...
Author: ml31415
Find elsewhere
🌐
Python
mail.python.org › pipermail › scipy-user › 2010-March › 024917.html
[SciPy-User] MATLAB accumarray equivalent ?
March 31, 2010 - and the way i used the accumarray in matlab was sth like this : (very simple example) >> subs = [1:6;6:-1:1] subs = 1 2 3 4 5 6 6 5 4 3 2 1 >> val = 10:15 val = 10 11 12 13 14 15 >> accumarray(subs',val) ans = 0 0 0 0 0 10 0 0 0 0 11 0 0 0 0 12 0 0 0 0 13 0 0 0 0 14 0 0 0 0 15 0 0 0 0 0 regards Mohammad On Wed, Mar 31, 2010 at 12:33 PM, Harald Schilly <harald.schilly at gmail.com>wrote: > On Wed, Mar 31, 2010 at 12:28, Mohammad Abdollahi <m.abdollahi at gmail.com> > wrote: > > but apparently they can not be used when subs > > is a matrix.
🌐
Reddit
reddit.com › r/matlab › what does accumarray([1,2,3], 1) do?
r/matlab on Reddit: What does accumarray([1,2,3], 1) do?
September 12, 2022 -

I tried with different values for the second argument but it just seems as if the value for the second argument ends up in the last output. Can't make sense out of it. Can someone give me a hint?

Edit. I guess if I vary the first argument to [2, 8] i get more insight, but not sure whether its the right one. Then the output is a 2 by 8 matrix with the second argument being the entry for a_{2,8}. why would one want that? especially compared to the use as a group count function in the first example in its documentation: https://www.mathworks.com/help/matlab/ref/accumarray.html

🌐
Stack Overflow
stackoverflow.com › questions › tagged › accumarray
Newest 'accumarray' Questions - Stack Overflow
I recently try to transfer some function from matlab to python. A function in matlab called "accumarray", accumarray(3d_array(10*10*10),1), the output is also 101010 3d array.
🌐
Google Groups
groups.google.com › g › comp.soft-sys.matlab › c › qFTW8pIMQsw
fast multithreaded option to accumarray or python equivalent of bincount
September 3, 2015 - I have read in the matlab central that the reason accumarray is not multithreaded is because it allows custom cell functions, etc and if only the two options are allowed, then it is easy to multi thread. Is there a function already that will do something like that? I was not sure if histcounts might work. For example, python numpy bincount equivalent which only takes index and weight as arguments.
🌐
PyPI
pypi.org › project › numpy-groupies
numpy-groupies · PyPI
aggregate takes an array of values, and an array giving the group number for each of those values. It then returns the sum (or mean, or std, or any, ...etc.) of the values in each group.
🌐
CSDN
devpress.csdn.net › python › 63045c49c67703293080bd0b.html
Is there a MATLAB accumarray equivalent in numpy?_python_Mangs-Python
August 23, 2022 - Answer a question I'm looking for a fast solution to MATLAB's accumarray in numpy. The accumarray accumulates the elements of an array which belong to the same index. An example: a = np.arange(1,11) # Mangs Python
🌐
PyTorch Forums
discuss.pytorch.org › vision
Analogue to accumarray (matlab) - sparse pooling - vision - PyTorch Forums
February 21, 2019 - Hi, I’m wondering if there’s a way to emulate the behavior of accumarray in Matlab. More specifically, my use case is to project 2D image features to the ground-plane as it has been done in MapNet. The exact specifications are as follows: Inputs: feat - image features with size (B, F, H, W) where B is batch-size and F is feature size loc - a tensor of locations with size (B, 2, H, W) where loc[b, :, i, j] gives a 2D coordinate output_dims - a tuple containing M, N (output dimensions) Outp...
🌐
Stack Overflow
stackoverflow.com › tags › accumarray › hot
Hottest 'accumarray' Answers - Stack Overflow
accumarray × 67 matlab × 65 matrix × 10 arrays × 9 grouping × 4 vectorization × 4 python × 3 numpy × 3 sum × 3 unique × 3 accumulate × 3 performance × 2 average × 2 octave × 2 sparse-matrix × 2 cumsum × 2 mysql × 1 dataframe × 1 multithreading × 1 function × 1 date × 1 recursion × 1 plot × 1 multidimensional-array × 1 audio × 1
🌐
Mathengineering
mathengineering.com › sparse-and-automatic-accumulation
Sparse and Automatic Accumulation – Mathematical Engineering
Current versions of MATLAB also contain a function called accumarray that performs the accumulation trick for non-sparse matrices (and you can change the accumulation function too).