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

Is there a shortcut to convert a binary (0 | 1) numpy array to integer or binary? Fe

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

np.packbits(b)

works, but only for 8-bit values. If numpy is equal to 9 or more elements, it generates 2 or more 8-bit values. Another option is to return the string 0 | 1...

What am I doing now:

    ba = bitarray()
    ba.pack(b.astype(np.bool).tostring())
    #convert from bitarray 0|1 to integer
    result = int( ba.to01(), 2 )

which is ugly !!!

+4
source share
3 answers

One way: dot-productwith a range array 2-powered-

b.dot(2**np.arange(b.size)[::-1])

Run Example -

In [95]: b = np.array([1,0,1,0,0,0,0,0,1,0,1])

In [96]: b.dot(2**np.arange(b.size)[::-1])
Out[96]: 1285

Alternatively, we could use the left-shift bitwise operator to create an array of ranges and thus get the desired result, for example:

b.dot(1 << np.arange(b.size)[::-1])

-

In [148]: b = np.random.randint(0,2,(50))

In [149]: %timeit b.dot(2**np.arange(b.size)[::-1])
100000 loops, best of 3: 13.1 µs per loop

In [150]: %timeit b.dot(1 << np.arange(b.size)[::-1])
100000 loops, best of 3: 7.92 µs per loop

, np.binary_repr np.fromstring -

In [96]: b = np.array([1,0,1,0,0,0,0,0,1,0,1])

In [97]: num = b.dot(2**np.arange(b.size)[::-1]) # integer

In [98]: np.fromstring(np.binary_repr(num), dtype='S1').astype(int)
Out[98]: array([1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1])
+5
def binary_converter(arr):
    total = 0
    for index, val in enumerate(reversed(arr)):
        total += (val * 2**index)
    print total


In [14]: b = np.array([1,0,1,0,0,0,0,0,1,0,1])
In [15]: binary_converter(b)
1285
In [9]: b = np.array([0,0,0,0,0,1,0,1])
In [10]: binary_converter(b)
5

b = np.array([1,0,1,0,0,0,0,0,1,0,1])
sum(val * 2**index for index, val in enumerate(reversed(b)))
0

numpy 64- . numpy, 64- , numpy:

import numpy as np
def bin2int(bits):
    return np.right_shift(np.packbits(bits, -1), bits.size).squeeze()

, numpy, , > 64- :

import gmpy2
def bin2int(bits):
    return gmpy2.pack(list(bits[::-1]), 1)

gmpy2, , > 64- :

def bin2int(bits):
    total = 0
    for shift, j in enumerate(bits[::-1]):
        if j:
            total += 1 << shift
    return total

, < **, .

0
source

Source: https://habr.com/ru/post/1663370/


All Articles