14

What is the most efficient way to remove negative elements in an array? I have tried numpy.delete and Remove all specific value from array and code of the form x[x != i].

For:

import numpy as np
x = np.array([-2, -1.4, -1.1, 0, 1.2, 2.2, 3.1, 4.4, 8.3, 9.9, 10, 14, 16.2])

I want to end up with an array:

[0, 1.2, 2.2, 3.1, 4.4, 8.3, 9.9, 10, 14, 16.2]
Community
  • 1
  • 1
Medulla Oblongata
  • 3,413
  • 7
  • 32
  • 58

4 Answers4

39
In [2]: x[x >= 0]
Out[2]: array([  0. ,   1.2,   2.2,   3.1,   4.4,   8.3,   9.9,  10. ,  14. ,  16.2])
Siegfried Gevatter
  • 3,504
  • 2
  • 16
  • 13
6

If performance is important, you could take advantage of the fact that your np.array is sorted and use numpy.searchsorted

For example:

In [8]: x[np.searchsorted(x, 0) :]
Out[8]: array([  0. ,   1.2,   2.2,   3.1,   4.4,   8.3,   9.9,  10. ,  14. ,  16.2])

In [9]: %timeit x[np.searchsorted(x, 0) :]
1000000 loops, best of 3: 1.47 us per loop

In [10]: %timeit x[x >= 0]
100000 loops, best of 3: 4.5 us per loop

The difference in performance will increase as the size of the array increases because np.searchsorted does a binary search that is O(log n) vs. O(n) linear search that x >= 0 is doing.

In [11]: x = np.arange(-1000, 1000)

In [12]: %timeit x[np.searchsorted(x, 0) :]
1000000 loops, best of 3: 1.61 us per loop

In [13]: %timeit x[x >= 0]
100000 loops, best of 3: 9.87 us per loop
Akavall
  • 76,296
  • 45
  • 192
  • 242
4

There's probably a cool way to do this is numpy because numpy is magic to me, but:

x = np.array( [ num for num in x if num >= 0 ] )
Adam Smith
  • 48,602
  • 11
  • 68
  • 105
4

In numpy:

b = array[array>=0]

Example:

>>> import numpy as np
>>> arr = np.array([-2, -1.4, -1.1, 0, 1.2, 2.2, 3.1, 4.4, 8.3, 9.9, 10, 14, 16.2])
>>> arr = arr[arr>=0]
>>> arr
array([  0. ,   1.2,   2.2,   3.1,   4.4,   8.3,   9.9,  10. ,  14. ,  16.2])
bitgarden
  • 10,159
  • 3
  • 16
  • 25