Take the 2-minute tour ×

I have two arrays, and I have a complex condition like this: new_arr<0 and old_arr>0 I am using nonzero but I am getting an error. The code I have is this:

    indices = nonzero(new_arr<0 and old_arr>0)

I tried:

    indices = nonzero(new_arr<0) and nonzero(old_arr>0)

But it gave me incorrect results.

Is there any way around this? And is there a way to get the common indices from two nonzero statements. For example, if:

    indices1 = nonzero(new_arr<0)
    indices2 = nonzero(old_arr>0)

and these two indices would contain:

   indices1 = array([0, 1, 3])
   indices2 = array([2, 3, 4])

The correct result would be getting the common element from these two (in this case it would be the element 3). Something like this:

    result = common(indices1, indices2)
share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

Try indices = nonzero((new_arr < 0) & (old_arr > 0)):

In [5]: import numpy as np

In [6]: old_arr = np.array([ 0,-1, 0,-1, 1, 1, 0, 1])

In [7]: new_arr = np.array([ 1, 1,-1,-1,-1,-1, 1, 1])

In [8]: np.nonzero((new_arr < 0) & (old_arr > 0))
Out[8]: (array([4, 5]),)
share|improve this answer
This is exactly what I was looking for. Never came to my mind using & instead of the good old and. Thanks! –  Don Code Jul 29 '11 at 16:00
+1, but only works if both input arrays are of the same shape (OP didn't mention any such assumption). –  Radim Jul 29 '11 at 16:02
@Radim: No such assumptions were mentioned, but if you're talking about "common indices", then you'd just end up resizing the larger array to the dimensions of the smaller one anyway. –  JAB Jul 29 '11 at 16:05
add comment


indices = nonzero(logical_and(new < 0, old > 0))

(Thinking about it, my previous example wasn't all that useful if all it did was return nonzero(condition) anyway.)

share|improve this answer
I dont' understand what you mean with condition.nonzero() –  Don Code Jul 29 '11 at 15:53
@theSun: modified my answer. –  JAB Jul 29 '11 at 15:58
This worked too, thanks! –  Don Code Jul 29 '11 at 16:04
add comment

Your Answer


