33

So I have these conditions:

A = 0 to 10 OR 40 to 60

B = 20 to 50

and I have this code:

area1 = N.where((A>0) & (A<10)),1,0)
area2 = N.where((B>20) & (B<50)),1,0)

My question is: how do I do 'OR' condition in numpy?

Community
  • 1
  • 1
rudster
  • 1,327
  • 4
  • 14
  • 16

2 Answers2

49

If numpy overloads & for boolean and you can safely assume that | is boolean or.

area1 = N.where(((A>0) & (A<10)) | ((A>40) & (A<60))),1,0)
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 1
    I think that `&` is bitwise and...which (in this case) is irrelevant since (A>0) is an array of `True`/`False` (i.e. `1`s and `0`s) – mgilson Apr 30 '12 at 00:31
  • 2
    One gotcha is to not forget to put the inequalities in parentheses because of their lower operation priority. – Roman Shapovalov Apr 04 '17 at 17:21
32

There's numpy.logical_or

http://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_or.html

numpy logical_and and logical_or are the ufuncs that you want (I think)

Note that & is not logical and, it is bitwise and. This still works for you because (a>10) returns a logical array (e.g. 1's and 0's) as does your second condition. So, in this case, "logical and" and "bitwise and" are equivalent (same with logical and bitwise or). But in other cases, the bitwise operations may yield surprising results (mostly because python's & and | operators have lower precedence than expected in these contexts).

mgilson
  • 300,191
  • 65
  • 633
  • 696