Convert binary (0|1) numpy to integer or binary-string?

前端 未结 5 1293
渐次进展
渐次进展 2021-02-19 20:29

Is there a shortcut to Convert binary (0|1) numpy array to integer or binary-string ? F.e.

b = np.array([0,0,0,0,0,1,0,1])   
  => b is 5

np.packbits(b)
         


        
5条回答
  •  终归单人心
    2021-02-19 20:59

    My timeit results:

    b.dot(2**np.arange(b.size)[::-1])
    100000 loops, best of 3: 2.48 usec per loop
    
    b.dot(1 << np.arange(b.size)[::-1])
    100000 loops, best of 3: 2.24 usec per loop
    
    # Precompute powers-of-2 array with a = 1 << np.arange(b.size)[::-1]
    b.dot(a)
    100000 loops, best of 3: 0.553 usec per loop
    
    # using gmpy2 is slower
    gmpy2.pack(list(map(int,b[::-1])), 1)
    100000 loops, best of 3: 10.6 usec per loop
    

    So if you know the size ahead of time, it's significantly faster to precompute the powers-of-2 array. But if possible, you should do all computations simultaneously using matrix multiplication like in Geoffrey Anderson's answer.

提交回复
热议问题