NumPy - 如何对矩阵行中的每个元素进行按位与操作

6

我希望寻求更好的方法对矩阵行中所有元素进行按位与运算。

我有一个数组:

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
axis=through_rows?你期望的输出结果是什么? - juanpa.arrivillaga
轴=1 -> 我想计算每一行样本中的A [0,0]&A [0,1]&A [0,2]&A [0,3]。 预期输出在每个示例下方。 - Jan
1个回答

10

为此专门设计的函数是bitwise_and.reduce

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

不幸的是,在numpy v1.12.0之前,bitwise_and.identity为1,因此这个方法行不通。对于那些老版本,可以使用以下解决方法:

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

1
对于具有通用维数的数组,我们可以使用 axis=-1 - Divakar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接