Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally select elements in numpy array

Can someone help me with conditionally selecting elements in a numpy array? I am trying to return elements that are greater than a threshold. My current solution is:

sampleArr = np.array([ 0.725, 0.39, 0.99 ])
condition = (sampleArr > 0.5)`
extracted = np.extract(condition, sampleArr) #returns [0.725 0.99]

However, this seems roundabout and I suspect there's a way to do it in one line?

like image 496
Trung Tran Avatar asked Feb 04 '18 16:02

Trung Tran


2 Answers

You can index directly like:

sampleArr[sampleArr > 0.5]

Test Code:

sampleArr = np.array([0.725, 0.39, 0.99])

condition = (sampleArr > 0.5)
extracted = np.extract(condition, sampleArr)  # returns [0.725 0.99]

print(sampleArr[sampleArr > 0.5])
print(sampleArr[condition])
print(extracted)

Results:

[ 0.725  0.99 ]
[ 0.725  0.99 ]
[ 0.725  0.99 ]
like image 59
Stephen Rauch Avatar answered Nov 15 '22 04:11

Stephen Rauch


You can actually just do boolean indexing like this:

extracted = sampleArr[sampleArr > 0.5]
like image 36
Banana Avatar answered Nov 15 '22 03:11

Banana