Home > OS >  How do I do pattern matching against a Numpy array?
How do I do pattern matching against a Numpy array?

Time:10-31

I'm a new Numpy user so I need some guidance.

Say I have this 3x3 matrix:

[[ -1,  1,  1],
 [ -1,  1,  1],
 [ -1, -1, -1]]

I want to detect a match with, for example, the following:

[[any,   1,   1],
 [any,   1,   1],
 [any, any, any]]

(In this case, the match will be True)

Is there a simple function / trick with Numpy to do this?

CodePudding user response:

You can use a mask and NaN:

a = np.array([[ -1,  1,  1],
              [ -1,  1,  1],
              [ -1, -1, -1]])

m = np.array([[np.nan,  1,  1],
              [np.nan,  1,  1],
              [np.nan, np.nan, -1]])

out = ((a == m) | np.isnan(m)).all()
# True
  • Related