whitebear
whitebear

Reputation: 12435

Comparing Numpy arrays like bit mask

I want to compare numpy array two scale and data

for exaple

scale = [1,0,0,0,1,0,0,0,1,0,0,0] first and fifth and ninth bit is 1

data1 = [8,2,0,1,0,0,1,0,1,0,0,0] -> NG, because fifth bit is `0`
data2 = [8,0,0,0,1,0,1,0,1,0,0,0] -> OK, because first ,fifth, ninth bit is more than 0

What I want to check is

Every positions where scale is 1 should be more than 0 in data

Is there any good numpy function to do this??

Upvotes: 0

Views: 241

Answers (1)

Rizquuula
Rizquuula

Reputation: 587

Step by step using Numpy:

  1. Convert to boolean, will return true when value > 0
  2. Bitwise AND
  3. Check equality
import numpy as np

scale = [1,0,0,0,1,0,0,0,1,0,0,0]
data1 = [8,2,0,1,0,0,1,0,1,0,0,0]
data2 = [8,0,0,0,1,0,1,0,1,0,0,0]

scale= np.array(scale, dtype=bool)
data1= np.array(data1, dtype=bool)
data2= np.array(data2, dtype=bool)

and1 = np.bitwise_and(scale, data1)
and2 = np.bitwise_and(scale, data2)

is_match1 = np.array_equal(scale, and1)
is_match2 = np.array_equal(scale, and2)

print(is_match1) # False
print(is_match2) # True

Upvotes: 2

Related Questions