NumPy - 如何按位和遍历矩阵行中的每个元素

时间:2017-01-20 10:32:52

标签: python numpy

我想要求更好的方法来按位和遍历矩阵行中的所有元素。

我有一个数组:

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 "<ipython-input-266-4186ceafed83>", line 13
dtype=np.uint16)
    ^
SyntaxError: invalid syntax

因为,numpy.bitwise_and(x1,x2 [,out])有两个数组作为输入。我怎样才能获得预期的输出?

1 个答案:

答案 0 :(得分:6)

此专用功能为bitwise_and.reduce

resultB = np.bitwise_and.reduce(B, axis=2)

不幸的是in numpy prior to v1.12.0 bitwise_and.identity是1,所以这不起作用。对于那些旧版本,解决方法如下:

resultB = np.bitwise_and.reduceat(B, [0], axis=2)