user5802211 - 2 months ago 21

Python Question

I have problem in interpret the numpy array in python, for example,

`data[:,i:i+3, j:j+3]`

if i =2, j =1, then it would be

`data[ :, 2: 5,1:4]`

suppose the whole data array look like this:

`data =([[ 0, 1, 2, 3, 4, 5],`

[10, 11, 12, 13, 14, 15],

[20, 21, 22, 23, 24, 25],

[30, 31, 32, 33, 34, 35],

[40, 41, 42, 43, 44, 45],

[50, 51, 52, 53, 54, 55]])

then what does the array

`data[ :, 2: 5,1:4]`

`:`

`,`

Answer

Here's a use of the index pattern:

Make a 3d array, with shape large enough to accommodate this index;

```
In [568]: data=np.arange(2*6*5).reshape(2,6,5)
In [569]: data[:, 2:5, 1:4]
Out[569]:
array([[[11, 12, 13],
[16, 17, 18],
[21, 22, 23]],
[[41, 42, 43],
[46, 47, 48],
[51, 52, 53]]])
```

The result is a (2,3,3) array. If we think of the 3d array as having planes, rows and columns, this returns all planes, 3 rows, and 3 columns. It may help to print out `data`

and identify the elements that have been selected. I made them unique to make this easier.

This is an example of basic indexing (all indexing terms are slices):

https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing-and-indexing