1

How can i go about converting a range of values inside a list(numpy array) of list to one number and leave all other numbers as they were, I tried the

np.where(array!= range(-1024,0),array,0))

but this one gives me an error,any suggestions on how i may do so,thanks in advance.

Ryan
  • 8,459
  • 14
  • 40
  • 66

3 Answers3

3

You can use isin i.e

array = np.array([-150,105,250,-520,-1024,-1050])

np.where( ~np.isin(array, np.arange(-1024,0)) , array, 0)

array([    0,   105,   250,     0,     0, -1050])
Bharath M Shetty
  • 30,075
  • 6
  • 57
  • 108
  • 2
    Just an additional note, if your `np.__version__` is smaller than `1.13`, you won't have `np.isin` but you'll get the same result using `np.in1d`. – FatihAkici Jan 04 '18 at 19:36
2

You can use

np.where(np.logical_and(a>=-1024 , a<=0),0,a)

This will check if the element of a is in the range [-1024,0] and make it 0 else leave it unchanged.

You can also refer this answer Numpy where function multiple conditions

Umang Gupta
  • 15,022
  • 6
  • 48
  • 66
0

Why not a simple list comprehension:

[e if e not in range(-1024,0) else 0 for e in array]

Or equivalently (more straightforward):

[0 if e in range(-1024,0) else e for e in array]

Edit: It may be argued that list-based answer is easier to read, but it is drastically slower than the numpy-based ones (think about 3.76 µs vs 453 µs!) So I'd stick with the numpy answers.

FatihAkici
  • 4,679
  • 2
  • 31
  • 48