Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting only those values that fulfill a condition in a numpy array

There must a be a (very) quick and efficient way to get only elements from a numpy array, or even more interestingly from a slice of it. Suppose I have a numpy array:

import numpy as np a = np.arange(-10,10) 

Now if I have a list:

s = [9, 12, 13, 14] 

I can select elements from a:

a[s]  #array([-1,  2,  3,  4]) 

How can I have an (numpy) array made of the elements from a[s] that fulfill a condition, i.e. are positive (or negative)? It should result

np.ifcondition(a[s]>0, a[s])  #array([2,  3,  4]) 

It looks trivial but I was not able to find a simple and condensed expression. I'm sure masks do but it's doesn't look really direct to me. However, neither:

a[a[s]>0] a[s[a[s]>0]] 

are in fact good choices.

like image 287
gluuke Avatar asked Oct 23 '12 11:10

gluuke


People also ask

How do you select a specific element in a NumPy array?

To select an element from Numpy Array , we can use [] operator i.e. It will return the element at given index only.

How do you select an element from an array?

You select a value from an array by referring to the index of its element. Array elements (the things inside your array), are numbered/indexed from 0 to length-1 of your array.


1 Answers

How about:

In [19]: b = a[s]  In [20]: b[b > 0] Out[20]: array([2, 3, 4]) 
like image 106
unutbu Avatar answered Oct 05 '22 23:10

unutbu