Numpy Binary Notation Fast Generation

Suppose I have a vector numpywith elements n, so I would like to encode the numbers in this vector as binary notation, so the final form will be (n,m)where mthere is log2(maxnumber)for example:

x = numpy.array([32,5,67])

Since I have the maximum number 67, I need numpy.ceil(numpy.log2(67)) == 7bits to encode this vector, so the form of the result will be(3,7)

array([[1, 0, 0, 0, 0, 1, 1],
       [0, 0, 0, 0, 1, 0, 1],
       [0, 1, 0, 0, 0, 0, 0]])

The problem grows because I have no quick way to move binary notation from
function numpy.binary_reprto numpy array. Now I need to iterate over the result and put each bit individually:

brepr = numpy.binary_repr(x[i],width=7)
j = 0
for bin in brepr:
   X[i][j] = bin
   j += 1

This is a very temporary and stupid way, how to make it effective?

+4
2

np.unpackbits :

>>> max_size = np.ceil(np.log2(x.max())).astype(int)
>>> np.unpackbits(x[:,None].astype(np.uint8), axis=1)[:,-max_size:]
array([[0, 1, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 1, 0, 1],
       [1, 0, 0, 0, 0, 1, 1]], dtype=uint8)
+3

numpy byte.

:

res = numpy.array(len(x),dtype='S7')
for i in range(len(x)):
    res[i] = numpy.binary_repr(x[i])

res = numpy.array([numpy.binary_repr(val) for val in x])
+1

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


All Articles