20

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?

2
  • 1
    why you needs numpy, you can't do it like this way ! filter(lambda a: 3 < a < 8, a) Commented Jul 14, 2010 at 17:41
  • 2
    @shahjapan - likely because they need the increased speed of a numpy array because they probably really have a much much larger dataset. Commented Jul 14, 2010 at 17:59

4 Answers 4

27
numpy.nonzero((a > 3) & (a < 8))

& does an element-wise boolean and.

Sign up to request clarification or add additional context in comments.

Comments

3

An alternative (which I ended up using) is numpy.logical_and:

choice = numpy.logical_and(np.greater(a, 3), np.less(a, 8))
numpy.extract(choice, a)

Comments

0

if you use numpy array, you can directly use '&' instead of 'and'.

a=array([1,2,3,4,5,6,7,8,9])
a[(a>3) & (a<8)]
ans=array([3,4,5,6])

Comments

0

Side note, this format works for any bitwise operation.

numpy.nonzero((a > 3) | (a < 8)) #[or]
numpy.nonzero((a > 3) & (a < 8)) #[and]

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.