Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode rows of boolean numpy array to bytes

Tags:

python

numpy

I have a numpy array of dimensions Nx8, with dtyp=boolean I want to convert it into a numpy 1-d array where each row is turned into a byte, by bin2dec

x = array([[ True,  True, False, False,  True,  True, False, False],
       [ False,  False, False, False,  True,  True, False, False],
       [ True,  False, False, False,  False,  False, False, False]], dtype=bool)

I'd like the output to be:

y = array([204 ,12, 128], dtype=uint8)
like image 947
eran Avatar asked May 25 '26 02:05

eran


1 Answers

>>> np.packbits(np.uint8(x))
array([204,  12, 128], dtype=uint8)

How that?

like image 146
Steve Barnes Avatar answered May 27 '26 16:05

Steve Barnes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!