lost_and_found
lost_and_found

Reputation: 47

Slicing 3d array list in Python

I am just moving into python3 from MATLAB. So my question may be silly, although I looked into the issue intensively but could not find a solution to my problem. So here is my problem - I have created a 3d array list using

routine_matrix = [[[0 for k in range(xaxis)] for j in range(yaxis)] for i in range(zaxis)]
routine_matrix[0][0][1] = 'aa'
routine_matrix[1][0][1] = 'bb'
routine_matrix[2][0][1] = 'cc'
routine_matrix[3][0][1] = 'dd'
routine_matrix[4][0][1] = 'ee'
routine_matrix[0][1][1] = 'ff'
routine_matrix[0][2][1] = 'gg'

And this is how the 3d list look like:

[[[0, 'aa', 0, 0], [0, 'ff', 0, 0], [0, 'gg', 0, 0]],
 [[0, 'bb', 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
 [[0, 'cc', 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
 [[0, 'dd', 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
 [[0, 'ee', 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]

Now if I want to access the elements 'aa', 'bb', 'cc', 'dd' and 'ee', using for loop I can easily do that using the following code:

for i in range(0,5):
    print(routine_matrix[i][0][1])

However, what I want to do is, I want to slice from the 3d list at one shot - something like:

print(routine_matrix[0:,0,1])

However, I am not getting my desired output. So all I am asking is how can I slice off 'aa', 'bb', 'cc', 'dd' and 'ee' at one go.

Thanks for your time!

Upvotes: 3

Views: 4785

Answers (1)

Arpit Agarwal
Arpit Agarwal

Reputation: 527

Maybe you figured out the answer but anyway here is my answer:

In 3d array the slicing syntax is denoted by [matrices, rows, columns]

import numpy as np

# Below we are creating a 3D matrix similar to your matrix where there are 
# 5 matrices each containing 3 rows and 4 columns

routine_matrix = np.arange(5*3*4).reshape((5,3,4))
print(routine_matrix) 

routine_matrix:

[[[ 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]]

 [[36 37 38 39]
  [40 41 42 43]
  [44 45 46 47]]

 [[48 49 50 51]
  [52 53 54 55]
  [56 57 58 59]]]

Now, As per your question you are interested in 1, 13, 25, 37, 49 that is first element of 0th row and 1st column of each internal matrix

So, in order to achieve that we do

print(routine_matrix[:, 0, 1])

Understand slicing here:

  • ':' says that choose all the matrices
  • '0' says that choose only the 0th row of all the matrices

i.e: [0 1 2 3], [12, 13, 14, 15], [24, 25, 26, 27], [36, 37, 38, 39], [48, 49, 50, 51]

  • '1' says that of all the rows selected above just choose the first column (Array index starts from 0 in python)

i.e: [1, 13, 25, 37, 49]

Hence the output:

[ 1 13 25 37 49]

In your case it will be ['aa' 'bb' 'cc' 'dd' 'ee']

Upvotes: 6

Related Questions