Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract the first 2 dimention of numpy array based on condtion on the 3rd dimention

Suppose that I have numpy array with 3 dimension [x,y,z], and I would like to extract the x and y dimension on a condition on the z dimension, for example, if z==1.
How Could I do that?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use numpy indexing for this. Consider an array:

a = np.arange(21).reshape((-1, 3))

# array([[ 0,  1,  2],
#       [ 3,  4,  5],
#       [ 6,  7,  8],
#       [ 9, 10, 11],
#       [12, 13, 14],
#       [15, 16, 17],
#       [18, 19, 20]])

Now you want a condition on the last column…say ever numbers:

    # all rows ⬎  ⬐ third column  
filtered = a[a[:, 2] % 2 == 0]
# array([[ 0,  1,  2],
#       [ 6,  7,  8],
#       [12, 13, 14],
#       [18, 19, 20]])

And just select the first two columns:

filtered[:,:2]   
# array([[ 0,  1],
#        [ 6,  7],
#        [12, 13],
#        [18, 19]])

This works because this gives an array of booleans…

i = a[:, 2] % 2 == 0
# array([ True, False,  True, False,  True, False,  True])

…which can then be used to index the original:

a[i]
# array([[ 0,  1,  2],
#        [ 6,  7,  8],
#        [12, 13, 14],
#        [18, 19, 20]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading