Can someone please explain to me how numpy indexing works for 2d arrays. I am finding it difficult to wrap my head around.
Specifically, if i create a 2d 8x8 array, what would each value represent in this instance:
array[x:y:i, t:n:m]
CodePudding user response:
In your array:
- The
x
andt
, are the beginning of the slice; - The
y
andt
, are the end of the slice; - The
i
andm
, are the step of the slice.
For example, let's define an 8x8 array:
z=[[x*y x y for x in range(8)] for y in range(8)]
z=np.asarray(z)
Out[1]:
array([[ 0, 1, 2, 3, 4, 5, 6, 7],
[ 1, 3, 5, 7, 9, 11, 13, 15],
[ 2, 5, 8, 11, 14, 17, 20, 23],
[ 3, 7, 11, 15, 19, 23, 27, 31],
[ 4, 9, 14, 19, 24, 29, 34, 39],
[ 5, 11, 17, 23, 29, 35, 41, 47],
[ 6, 13, 20, 27, 34, 41, 48, 55],
[ 7, 15, 23, 31, 39, 47, 55, 63]])
z.shape
Out[2]: (8, 8)
From row 0 until row 3 (excluding it) every 2 rows, will index like:
z[0:3:2]
Out[3]:
array([[ 0, 1, 2, 3, 4, 5, 6, 7],
[ 2, 5, 8, 11, 14, 17, 20, 23]])
For columns:
z[:,1:6:3]
Out[4]:
array([[ 1, 4],
[ 3, 9],
[ 5, 14],
[ 7, 19],
[ 9, 24],
[11, 29],
[13, 34],
[15, 39]])
Combining rows and columns:
z[0:3:2, 0:3:2]
Out[5]:
array([[0, 2],
[2, 8]])