18

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]

4 Answers 4

46
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])
Sign up to request clarification or add additional context in comments.

2 Comments

what exactly would you call this operation? I'm interested in learning exactly how it works
its numpy.where (shortcut) and numpy slicing combined
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

Comments

5

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])

Comments

3

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 ] )

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.