Inverse of numpy's bincount function

后端 未结 3 995
清酒与你
清酒与你 2020-12-11 08:13

Given an array of integer counts c, how can I transform that into an array of integers inds such that np.all(np.bincount(inds) == c) i

相关标签:
3条回答
  • 2020-12-11 08:41

    The following is about twice as fast on my machine than the currently accepted answer; although I must say I am surprised by how well np.repeat does. I would expect it to suffer a lot from temporary object creation, but it does pretty well.

    import numpy as np
    c = np.array([1,3,2,2])
    p = np.cumsum(c)
    i = np.zeros(p[-1],np.int)
    np.add.at(i, p[:-1], 1)
    print np.cumsum(i)
    
    0 讨论(0)
  • 2020-12-11 08:55

    no numpy needed :

    c = [1,3,2,2]
    reduce(lambda x,y: x + [y] * c[y], range(len(c)), [])
    
    0 讨论(0)
  • 2020-12-11 09:00

    using numpy.repeat :

    np.repeat(np.arange(c.size), c)
    
    0 讨论(0)
提交回复
热议问题