0

I'm new to this, so this is probably a basic question, but how do I remove values from my array that are less than 0?

So, if

a=np.random.randint(-10,11,(10,10))

How would I create an array with only the positive values from a? thanks

Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
  • 2
    Does this answer your question? [How to remove specific elements in a numpy array](https://stackoverflow.com/questions/10996140/how-to-remove-specific-elements-in-a-numpy-array) – pierre Mar 04 '21 at 13:42
  • Do you want elements smaller than zero to be set to 0? in that case something like `a[a<0]=0` should work – joostblack Mar 04 '21 at 14:04

3 Answers3

1
import numpy as np
a=np.random.randint(-10,11,(10,10))
np.where(a > 0, a, 0)
Zeinab Mardi
  • 133
  • 1
  • 5
1

The native python way to do it would be a comprehension list :

filtered = [x for x in a if x>0]

For numpy ways of doing it have a look at this similar question : Filtering a NumPy Array: what is the best approach?

0

In Numpy you can use what is known as fancy indexing for this kind of tasks.

In [26]: a = np.random.randint(-10,11,(10,10))

In [27]: a
Out[27]:
array([[ -6,   2,   8,  -8,  -7,   7,   5,   0,  10,   5],
       [ -3,  -7,   5,   0,   3,   7,   3,  10,  -9,   0],
       [  1,   8,  -8,  -2,   4,   2,  -7,  10,  -3,  -5],
       [  7,   1,   3,  -2,   1,   8,   7,   6,  -4,   0],
       [ -5,   6,  -2,  -7, -10,  -9,   9,   9,  -5,   8],
       [  4,   3,  -7,   1,   4,   1,  -6,   7,  -6,  -5],
       [ -5,  -5,   4,  -7,  -6,  -6,  10,  -2,  -8,   8],
       [ -9,   4,   2,  10,  -7,  -5,   3,   5,   9,   1],
       [ -9,  -7,  -3,  -8,  -4,  -7,  -6,  -5,   1,  -9],
       [ -7,  -4,  -8,   5, -10,   1,   2,  -8,  -2,  10]])

In [28]: a[a!=0] #this is the fancy indexing (non 0 elements)
Out[28]:
array([ -6,   2,   8,  -8,  -7,   7,   5,  10,   5,  -3,  -7,   5,   3,
         7,   3,  10,  -9,   1,   8,  -8,  -2,   4,   2,  -7,  10,  -3,
        -5,   7,   1,   3,  -2,   1,   8,   7,   6,  -4,  -5,   6,  -2,
        -7, -10,  -9,   9,   9,  -5,   8,   4,   3,  -7,   1,   4,   1,
        -6,   7,  -6,  -5,  -5,  -5,   4,  -7,  -6,  -6,  10,  -2,  -8,
         8,  -9,   4,   2,  10,  -7,  -5,   3,   5,   9,   1,  -9,  -7,
        -3,  -8,  -4,  -7,  -6,  -5,   1,  -9,  -7,  -4,  -8,   5, -10,
         1,   2,  -8,  -2,  10])


In [29]: a[a>0] #fancy indexing again (all positive elements)
Out[29]:
array([ 2,  8,  7,  5, 10,  5,  5,  3,  7,  3, 10,  1,  8,  4,  2, 10,  7,
        1,  3,  1,  8,  7,  6,  6,  9,  9,  8,  4,  3,  1,  4,  1,  7,  4,
       10,  8,  4,  2, 10,  3,  5,  9,  1,  1,  5,  1,  2, 10])
alec_djinn
  • 10,104
  • 8
  • 46
  • 71