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?
You can index directly like:
sampleArr[sampleArr > 0.5]
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)
[ 0.725 0.99 ]
[ 0.725 0.99 ]
[ 0.725 0.99 ]
You can actually just do boolean indexing like this:
extracted = sampleArr[sampleArr > 0.5]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With