我想要求更好的方法来按位和遍历矩阵行中的所有元素.
我有一个数组:
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)
示例和预期输出:
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]]])
但我的输出是:
resultA = np.bitwise_and(A, axis=through_rows) # doesn't work File "", line 13 dtype=np.uint16) ^ SyntaxError: invalid syntax
因为,numpy.bitwise_and(x1,x2 [,out])有两个数组作为输入.如何获得预期的输出?
专用功能是bitwise_and.reduce
:
resultB = np.bitwise_and.reduce(B, axis=2)
不幸的是,在v1.12.0之前的numpy bitwise_and.identity
是1,所以这不起作用.对于那些旧版本,解决方法如下:
resultB = np.bitwise_and.reduceat(B, [0], axis=2)