I'd like to ask for better way to bitwise and over all elements in matrix rows.
I have an array:
import numpy as np
A = np.array([[1,1,1,4], #shape is (3, 5) - one sample
[4,8,8,16],
[4,4,4,4]],
dtype=np.uint16)
B = np.array([[[1,1,1,4], #shape is (2, 3, 5) - two samples
[4,8,8,16],
[4,4,4,4]],
[[1,1,1,4],
[4,8,8,16],
[4,4,4,4]]]
dtype=np.uint16)
Example and expected output:
resultA = np.bitwise_and(A, axis=through_rows) # doesn't work
# expected output should be a bitwise and over elements in rows resultA:
array([[0],
[0],
[4]])
resultB = np.bitwise_and(B, axis=through_rows) # doesn't work
# expected output should be a bitwise and over elements in rows
# for every sample resultB:
array([[[0],
[0],
[4]],
[[0],
[0],
[4]]])
But my output is:
resultA = np.bitwise_and(A, axis=through_rows) # doesn't work
File "<ipython-input-266-4186ceafed83>", line 13
dtype=np.uint16)
^
SyntaxError: invalid syntax
Because, numpy.bitwise_and(x1, x2[, out]) have two array as input. How can I get my expected output?
The dedicated function for this would be bitwise_and.reduce
:
resultB = np.bitwise_and.reduce(B, axis=2)
Unfortunately in numpy prior to v1.12.0 bitwise_and.identity
is 1, so this doesn't work. For those older versions a workaround is the following:
resultB = np.bitwise_and.reduceat(B, [0], axis=2)
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