Is there a MATLAB accumarray equivalent in numpy?

后端 未结 7 1740
时光说笑
时光说笑 2021-01-01 18:06

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 exampl

7条回答
  •  感动是毒
    2021-01-01 18:46

    How about the following:

    import numpy
    
    def accumarray(a, accmap):
    
        ordered_indices = numpy.argsort(accmap)
    
        ordered_accmap = accmap[ordered_indices]
    
        _, sum_indices = numpy.unique(ordered_accmap, return_index=True)
    
        cumulative_sum = numpy.cumsum(a[ordered_indices])[sum_indices-1]
    
        result = numpy.empty(len(sum_indices), dtype=a.dtype)
        result[:-1] = cumulative_sum[1:]
        result[-1] = cumulative_sum[0]
    
        result[1:] = result[1:] - cumulative_sum[1:]
    
        return result
    

提交回复
热议问题