Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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?

like image 462
Jan Avatar asked Jan 20 '17 10:01

Jan


1 Answers

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)
like image 68
user7138814 Avatar answered Oct 12 '22 22:10

user7138814