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?
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)
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]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With