Indexing And Slicing A Numpy Array

As a first step, import numpy library into the program:

import numpy as np 

1. INDEXING IN NUMPY

We have studiedarrow-up-right indexing techniques in Python list, a similar approach is taken for indexing Numpy array.

Indexing means to access the single element in the array, at a given position,

  • For 1D array, it is similar to indexing Python’s list

  • For nD array, it is similar to indexing Python’s lists of lists

1.1. On 1D array

# creating an array
arr1d = np.arange(1,11)
print(f"This is the array: {arr1d}")

# fetching first item in array
print(f"\nFirst Item in the array: {arr1d[0]}")
# fetching last item in array
print(f"\nLast Item in the array: {arr1d[-1]}")
# fetching middle item in array
print(f"\nMiddle Item in the array: {arr1d[int((arr1d.size/2)-1)]}") 

1.2. On nD array

a. 2D array

For 2D array, we need to provide the position in (x,y) scheme, where x is the x-axis position, and y is the position on y-axis

b. 3D array

For 3D array, we need to provide the position in (a,x,y) scheme, where a is position of matrix, x is the x-axis position, and y is the position on y-axis

2. SLICING IN NUMPY

Slicing means to access subarray from the main array. We use [:] slice notion to perform slicing. Remember that slicing return views rather than copies of the array data. The standard format for slicing is:

1darray[start:stop:step]

The default value for start=0, step=1 and stop=index position before to stop

2.1. On 1D array

We will use the following syntax: 1darray[start:stop:step]

Reversing the order: By providing step=-1, we reverse the order of elements in the array

2.2. On nD array

In this section, we move from 1D arrays to arrays with more than 1 dimension.

a. 2D array

For 2D array, we will use the same syntax for slicing, but each axis slicing point is separated by comma

2darray[start:stop:step, start:stop:step]

Reversing in 2D array We will reverse:

  • both rows and columns values,

  • only rows,

  • only column

b. 3D array

For 3D array, we will use the same syntax for slicing, but each axis slicing point is separated by comma

3darray[start:stop:step, start:stop:step, start:stop:slice]

Reversing the 3D array

Last updated