Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find decimal value of 1D binary array in numpy Python

I have a boolean numpy array like this,

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

and another 1D array like this,

>>> another_arr
array([128,  64,  32,  16,   8,   4,   2,   1])

I want to somehow do some and or addition to get only values where that 1 is present something like,

>>> np_arr
array([[128,64,32,8, 0, 0, 2, 1],
       [128,64,32,8, 0, 0, 2, 1],
         ....................
       [128,64,32,8, 0,4, 0, 0],
        .....................)

So then I can then sum them to find the binary value of the each 1D array in the 2D array.. Or is some simple way to get decimal value numpy array as result?

like image 969
poda_badu Avatar asked Sep 23 '26 17:09

poda_badu


2 Answers

What you need is probably this:

import numpy as np


ar = np.array([[1, 1, 1, 1, 0, 0, 1, 1],
               [1, 1, 1, 1, 0, 0, 1, 1],
               [1, 1, 1, 1, 0, 0, 1, 1],
               [1, 1, 1, 1, 0, 0, 1, 1],
               [1, 1, 1, 1, 0, 0, 1, 1],
               [1, 1, 1, 1, 0, 1, 0, 0],
               [1, 1, 1, 1, 0, 1, 0, 0],
               [1, 1, 1, 1, 0, 1, 0, 0]])

np.packbits(ar, axis=-1)

Result:

array([[243],
       [243],
       [243],
       [243],
       [243],
       [244],
       [244],
       [244]], dtype=uint8)
like image 146
Vasyl Bratushka Avatar answered Sep 25 '26 08:09

Vasyl Bratushka


This is one way. It works because numpy broadcasts implicitly.

import numpy as np

mask = np.array([[1, 1, 1, 1, 0, 0, 1, 1],
                 [1, 1, 1, 1, 0, 0, 1, 1],
                 [1, 1, 1, 1, 0, 0, 1, 1],
                 [1, 1, 1, 1, 0, 0, 1, 1],
                 [1, 1, 1, 1, 0, 0, 1, 1],
                 [1, 1, 1, 1, 0, 1, 0, 0],
                 [1, 1, 1, 1, 0, 1, 0, 0],
                 [1, 1, 1, 1, 0, 1, 0, 0]])

arr = np.array([128,  64,  32,  16,   8,   4,   2,   1])

arr2 = arr * mask

# array([[128,  64,  32,  16,   0,   0,   2,   1],
#        [128,  64,  32,  16,   0,   0,   2,   1],
#        [128,  64,  32,  16,   0,   0,   2,   1],
#        [128,  64,  32,  16,   0,   0,   2,   1],
#        [128,  64,  32,  16,   0,   0,   2,   1],
#        [128,  64,  32,  16,   0,   4,   0,   0],
#        [128,  64,  32,  16,   0,   4,   0,   0],
#        [128,  64,  32,  16,   0,   4,   0,   0]])
like image 30
jpp Avatar answered Sep 25 '26 06:09

jpp



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!