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

2
  • 2
    Does this answer your question? How to remove specific elements in a numpy array Commented Mar 4, 2021 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 Commented Mar 4, 2021 at 14:04

3 Answers 3

1
import numpy as np
a=np.random.randint(-10,11,(10,10))
np.where(a > 0, a, 0)
Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

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

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.