Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python removing all negative values in array

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]
like image 451
Medulla Oblongata Avatar asked Apr 15 '14 23:04

Medulla Oblongata


2 Answers

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])
like image 122
Siegfried Gevatter Avatar answered Sep 18 '22 23:09

Siegfried Gevatter


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
like image 24
Akavall Avatar answered Sep 22 '22 23:09

Akavall