8

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?

2 Answers 2

13

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 ]
Sign up to request clarification or add additional context in comments.

3 Comments

why 2d array select becomes 1d array?
@CSQGB I do not see any 2d arrays here.
what about multiple conditions?
2

You can actually just do boolean indexing like this:

extracted = sampleArr[sampleArr > 0.5]

3 Comments

You have the same answer :P
why 2d array select becomes 1d array?z=numpy.random.randint(1,9,(4,4)) z[z>4] array([ 5, 6, 7, 8, 9, 10, 11, 12]) . Not 2d array
@CSQGB Not a real explanation but this can never work since it would generally have to result in rows/columns of uneven length. You can use np.argwhereto find positions of elements satisfying the condition or use the z>4 mask and loop through it when required.

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.