understanding the dimensions in python arrays is a little bit tricky. one should understand its basics before jumping into its application and making operations.
prerequisite: having idea behind basic array in numpy, coding in python
let understand it through an example:
suppose we have a 2d array denoted by np_array_2d in a python program:
[[0 1 2]
[3 4 5]]
we want to apply some basic operations like a sum:
np.sum(np_array_2d, axis = 0)
so what it does is that it collapses the row and the output will be:
>>[3,5,7]
is actually respect that rule of 0 indicates the row and 1 indicates column but understanding it through collapses, you may find it difficult.
It is the same for the column, i.e:
np.sum(np_array_2d, axis = 1)
output>>[3, 12]
it was an example of 2d array. now let’s go for a 3d example , array variable name is np_array_3d:
import numpy as np
np_array_3d=np.array(
[[[0,1,2],[3,4,5],[6,7,8]],
[[0,1,2],[3,4,5],[6,7,8]],
[[0,1,2],[3,4,5],[6,7,8]]])
a=np.sum(np_array_3d, axis = (0))
print(np_array_3d.shape)
print(a.shape)
print(a)
the output will be:
(3, 3, 3)
(3, 3)
[[ 0 3 6]
[ 9 12 15]
[18 21 24]]
here we have collapsed the 0 dimensions to apply the operations(in here it is sum) and the remaining y,z, and will catch the collapsed summed value.in simple words, the parameters of the axis (e.g: axis=0,1…..) indicated the dimension to collapse. and the remaining dimension will store its corresponding summed value.
now we will do another experiment :
a=np.sum(np_array_3d, axis = (0,1))
print(a)
the output will be:
[27 36 45]
x and y collapse and put the summed value in its corresponding z(or 3d dimension array).
here is another:
a=np.sum(np_array_3d, axis = (0,1,2))
print(a)
this will output a single value because all three dimensions are collapsed.
output: 108