3

I have two boolean numpy arrays of similar shape like:

a=[[True,True,False,False]]
b=[[True,False,True,False]]

How can I get an array c where 1 indicates that only array a is true, 2 indicates that only array b is true, 0 where both arrays are false and nan where both are true. So in this case the result should be [[nan,1,2,0]]].

2
  • 1
    What if both are True? Commented Dec 7, 2015 at 11:30
  • I've updated the question: if both are true an 'nan' should be returned Commented Dec 7, 2015 at 11:33

2 Answers 2

4

You could use np.select:

In [20]: a = np.array([True,True,False,False])

In [21]: b = np.array([True,False,True,False])

In [23]: np.select([a&~b, b&~a, a&b], [1, 2, np.nan], default=0)
Out[23]: array([ nan,   1.,   2.,   0.])
Sign up to request clarification or add additional context in comments.

Comments

4

You could use np.where -

np.where(a*b,np.nan,(2*b + a))

Sample run -

In [60]: a
Out[60]: array([[ True,  True, False, False]], dtype=bool)

In [61]: b
Out[61]: array([[ True, False,  True, False]], dtype=bool)

In [62]: np.where(a*b,np.nan,(2*b + a))
Out[62]: array([[ nan,   1.,   2.,   0.]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.