3

I have an array and want ot extract all entries which are in a specific range

x = np.array([1,2,3,4])
condition = x<=4 and x>1
x_sel = np.extract(condition,x)

But this does not work. I'm getting

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

If I'm doing the same without the and and checking for example only one condition

x = np.array([1,2,3,4])
condition = x<=4 
x_sel = np.extract(condition,x)

everything works... Of courese I could just apply the procedure twice with one condition, but isn't there a solution to do this in one line?

Many thanks in advance

Jan SE
  • 337
  • 5
  • 13

2 Answers2

7

You can use either this:

import numpy as np

x = np.array([1,2,3,4])
condition = (x <= 4) & (x > 1)
x_sel = np.extract(condition,x)
print(x_sel)
# [2 3 4]

Or this without extract:

x_sel = x[(x > 1) & (x <= 4)]
Austin
  • 25,759
  • 4
  • 25
  • 48
4

This should work:

import numpy as np

x = np.array([1,2,3,4])
condition = (x<=4) & (x>1)
x_sel = np.extract(condition,x)

Mind the usage of and and &: Difference between 'and' (boolean) vs. '&' (bitwise) in python. Why difference in behavior with lists vs numpy arrays?

Fourier
  • 2,795
  • 3
  • 25
  • 39