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

How to select elements from a multidimensional array with python : array[:][i][j]?

In Python, I have a 3 dimensional array A :

A=np.random.random((3,2,3))

print(A)

Out[6]: [[[0.89565135 0.79502322 0.89015957]
  [0.40303084 0.80496231 0.50278239]]

 [[0.70610822 0.61269108 0.00470925]
  [0.29734101 0.67986295 0.34584381]]

 [[0.71822397 0.99326199 0.40949422]
  [0.97733739 0.38916931 0.91475145]]]

I would like to select the first element of each submatrix and to make an array from them [0.89565135,0.70610822,0.71822397] so I tried the following formula : A[:][0][0],A[0][:][0],A[0][0][:] but they all give me the same result, which is not the one I’m expecting…

A[:][0][0]
Out[7]: array([0.89565135, 0.79502322, 0.89015957])

A[0][:][0]
Out[8]: array([0.89565135, 0.79502322, 0.89015957])

A[0][0][:]
Out[9]: array([0.89565135, 0.79502322, 0.89015957])

What formula can I use to get the right array and how come the above formula give the same result ?

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

>Solution :

You can do as follows to select for all channel, the first element of the matrix:

A[:, 0, 0]

: references all channels, 0 the first row and 0 the first column.

Output:

array([0.89565135,0.70610822,0.71822397])

EDIT:

If your are working with nested list, you can do as follows:

[array[0][0]for array in A]

This shows one of the benefit of numpy array over python list as the selection is much more easier (and faster) using numpy.

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