tags:

views:

80

answers:

2

I have an array

a=[1,2,3,4,5,6,7,8,9]

and I want to find the indices of the element s that meet two conditions i.e.

a>3 and a<8
ans=[3,4,5,6]
a[ans]=[4,5,6,7]

I can use numpy.nonzero(a>3) or numpy.nonzero(a<8) but not numpy.nonzero(a>3 and a<8) which gives the error:

ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()

When I try to use any or all I get the same error. Is it possible to combine two conditional tests to get the ans?

+5  A: 
numpy.nonzero((a > 3) & (a < 8))

& does an element-wise boolean and.

Matthew Flaschen
Thanks Matthew, worked like a charm!
David
A: 

For the example you gave, can't you use something like:

numpy.nonzero(3 < a < 8)
Sean O'Hollaren
No, for the same reason why the OP's original suggestion doesn't work—in fact, your code is equivalent to the original suggestion.
Philipp
I stand corrected.
Sean O'Hollaren