Trung Tran
Trung Tran

Reputation: 13721

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?

Upvotes: 8

Views: 21191

Answers (2)

Banana
Banana

Reputation: 1187

You can actually just do boolean indexing like this:

extracted = sampleArr[sampleArr > 0.5]

Upvotes: 2

Stephen Rauch
Stephen Rauch

Reputation: 49794

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 ]

Upvotes: 13

Related Questions