1

I believe similar questions have been asked but none which deal with the problem I am facing.

I have an array of shape (H,W,L) - I must loop through each instance of the array to filter out values (their x,y location) that meet a particular criteria. (say val > t_r and val < t_c) - I must repeat this for each of the K values.

For eg: If we have an array of shape (2,3,4)

A = [[[1,2,3,], [3,4,5,]], 
        [[6,7,8],[1,4,5]], 
        [[5,7,7],[9,4,3]],
        [[1,2,4],[4,6,7]]]

suppose the first criteria is val > 2 and the second criteria is val < 6 and store the (row, col) value in a N x 3 array. Where the first 2 values are the 'row','col' and the last one corresponds to the layer / third dimension. then the expected output of the operation should be something like -

output = [[0,2,0],[1,0,0],[1,0,0],[1,1,0],[1,2,0]....] this would correspond to the values filtered from A[:,:,0]

One approach I have thought of is - using 3 for loops - i,j,k to loop over each of the elements, but I am unable to figure out the exact implementation. I would also like to implement vectorization wherever possible. I could use some guidance.

1
  • 1
    Just a general remark: you almost never need loops with NumPy. Commented Oct 3, 2019 at 11:49

1 Answer 1

1

You may use np.nonzero and vectorize your comparisons.

a = np.asarray(A)
res = np.vstack(np.nonzero((a>2)&(a<6))).T

array([[0, 0, 2],
       [0, 1, 0],
       [0, 1, 1],
       [0, 1, 2],
       [1, 1, 1],
       [1, 1, 2],
       [2, 0, 0],
       [2, 1, 1],
       [2, 1, 2],
       [3, 0, 2],
       [3, 1, 0]], dtype=int64)

You can always reorder the columns to your liking e.g.:

res[:, [1,2,0]]

array([[0, 2, 0],
       [1, 0, 0],
       [1, 1, 0],
       [1, 2, 0],
       [1, 1, 1],
       [1, 2, 1],
       [0, 0, 2],
       [1, 1, 2],
       [1, 2, 2],
       [0, 2, 3],
       [1, 0, 3]], dtype=int64)
Sign up to request clarification or add additional context in comments.

Comments

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.