1

Say I have a 3D array such as:

>>> arr = numpy.arange(36).reshape(3, 4, 3)
>>> arr
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8],
        [ 9, 10, 11]],

       [[12, 13, 14],
        [15, 16, 17],
        [18, 19, 20],
        [21, 22, 23]],

       [[24, 25, 26],
        [27, 28, 29],
        [30, 31, 32],
        [33, 34, 35]]])

How do I extract the nth value from each innermost row?

If I were to take the values for index 1, how can pull out the following?

array([[ 1,  4,  7, 10],
       [13, 16, 19, 22],
       [25, 28, 31, 34]])

or

array([ 1,  4,  7, 10, 13, 16, 19, 22, 25, 28, 31, 34])
Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144

2 Answers2

3

TLDR:

arr[:,n]       # for 2d
arr[:,:,n]     # for 3d
arr[:,:,:,n]   # for 4d
arr[:,:,:,:,n] # for 5d

You can access using the last index:

import numpy

arr = numpy.arange(36).reshape(3, 4, 3)

print(arr[:, :, 1])

Output

[[ 1  4  7 10]
 [13 16 19 22]
 [25 28 31 34]]

Or,

print(arr[:, :, 1].flatten())

Output

[ 1  4  7 10 13 16 19 22 25 28 31 34]

You can find more information about numpy indexing here.

UPDATE

As mentioned by @MadPhysicist in the comments, you can use ravel instead of flatten, the main difference is that flatten returns a copy and ravel returns a view. Also you can use an arr[..., 1] to access the last index, known as an ellipsis. From the documentation:

Ellipsis expand to the number of : objects needed to make a selection tuple of the same length as x.ndim

Further

Maifee Ul Asad
  • 3,992
  • 6
  • 38
  • 86
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
-1

To extract elements from such array you can do the following:

>>> import numpy as np   
>>> arr = np.arange(36).reshape(3, 4, 3)
>>> arr[:,:,1]
array([[ 1,  4,  7, 10],
       [13, 16, 19, 22],
       [25, 28, 31, 34]])

and if you want the flattened array you can do:

>>> arr.flatten()
array([ 1,  4,  7, 10, 13, 16, 19, 22, 25, 28, 31, 34])