繁体   English   中英

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

[英]NumPy - How to bitwise and over each element in matrix rows

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

我有一个数组:

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])有两个数组作为输入。 如何获得预期的输出?

这个的专用函数是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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM