Increment Numpy array with repeated indices

前端 未结 4 655
渐次进展
渐次进展 2020-11-28 13:52

I have a Numpy array and a list of indices whose values I would like to increment by one. This list may contain repeated indices, and I would like the increment to scale wit

相关标签:
4条回答
  • 2020-11-28 14:07

    In numpy >= 1.8, you can also use the at method of the addition 'universal function' ('ufunc'). As the docs note:

    For addition ufunc, this method is equivalent to a[indices] += b, except that results are accumulated for elements that are indexed more than once.

    So taking your example:

    a = np.zeros(6).astype('int')
    b = [3, 2, 5, 2]
    

    …to then…

    np.add.at(a, b, 1)
    

    …will leave a as…

    array([0, 0, 2, 1, 0, 1])
    
    0 讨论(0)
  • 2020-11-28 14:09

    If b is a small subrange of a, one can refine Alok's answer like this:

    import numpy as np
    a = np.zeros( 100000, int )
    b = np.array( [99999, 99997, 99999] )
    
    blo, bhi = b.min(), b.max()
    bbins = np.bincount( b - blo )
    a[blo:bhi+1] += bbins
    
    print a[blo:bhi+1]  # 1 0 2
    
    0 讨论(0)
  • 2020-11-28 14:17

    Why not?

    for i in b:
        a[i] += 1
    
    0 讨论(0)
  • 2020-11-28 14:23

    After you do

    bbins=np.bincount(b)
    

    why not do:

    a[:len(bbins)] += bbins
    

    (Edited for further simplification.)

    0 讨论(0)
提交回复
热议问题