0

I know that I can use a relational operator on my array to get a new array of Boolean values. The example below produces a boolean array with an identical shape to the original array but with True values if the item at the same index is greater than 0 and False otherwise.

>>> a = np. array ([ [0 , -2 ,5] , [ -1 , -8 , -12] ,[2 , 4, -9] ])
>>> z = a > 0
>>> print (a)
[[ 0 2 5]
[ 1 -8 -12]
[ 2 4 -9]]
>>> print (z)
[[ False True True ]
[ True False False ]
[ True True False ]]

What I'm wondering is if there's a way to simultaneously compare multiple indices to check if two or more values are greater than 0. For example, a line which would check each row to see if the first element and second element are greater than 0. Something than would look like

z = a[:,0] > 0 and a[:,1] > 0

And would produce the result

array([False, False,  True])

because a[0,1] = True but a[0,0] = False, a[1,0] = True but a[0,1] = False, and both a[2,0] and a[0,2] are True, thus returning False for the first row, False for the second row, and True for the third row


I want to do all of this without a loop

2
  • np.logical_and(a[:, 0] > 0, a[:, 1] > 0)? Commented Oct 31, 2019 at 18:27
  • 1
    (a[:,0]>0) & (a[:,1]>0) - group the comparisons with () and combine with an elementwise & (or |). Commented Oct 31, 2019 at 18:35

2 Answers 2

1

Simply use logical_and

It will compute 'logical &' element wise.

np.logical_and(a[:,0] > 0, a[:,1] > 0)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I realize that the title to my question isn't very clear, can you think of a better title that would be more descriptive?
-1

Not exactly a loop:

[b[0] > 0 and b[1] > 0 for b in a]

1 Comment

but awfully close - the for b in a is an iteration.

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.