/    /  NumPy – Indexing & Slicing

NumPy – Indexing & Slicing:

In this tutorial, we will learn about indexing and slicing of data in NumPy.

In NumPy, very efficient and optimized indexing can be done by using various functions which are provided in the package.

Let us understand indexing with Numpy by creating an array of one-dimensional and accessing all the values.

Example:

>>> a=np.arange(5)

>>> a
array([0, 1, 2, 3, 4])

>>> a[0]
0

>>> a[1]
1

>>> a[2]
2

# 5th position does not exists. Hence the error below.

>>> a[5]
Traceback (most recent call last):
File "<pyshell#112>", line 1, in <module>
a[5]
IndexError: index 5 is out of bounds for axis 0 with size 5

>>> a[-1]
4

>>> a[-2]
3

>>> a[-3]
2

>>> a[-4]
1

>>> a[-5]
0

>>>

Now let us try with Multi-Dimensional Array.

We are creating an array with diag function to create a 3 by 3 matrix form and the values given will be placed in the diagonal section of the matrix.

In the Multi-dimensional Array,

The dimension corresponding to rows can be interpreted by using a[0] (First row of all elements)
The column axis

>>> a=np.diag(np.arange(3))

>>> a
array([[0, 0, 0],
[0, 1, 0],
[0, 0, 2]])

>>> a[0]
array([0, 0, 0])

>>> a[1]
array([0, 1, 0])

>>> a[2]
array([0, 0, 2])

# To access the column axis, we need to mention the specified index number to access the value.

>>> a[1,1]
1

>>> a[1,2]
0

# below is the error just because we tried to access the 3rd position value in the column which is not existing.

>>> a[1,3]
Traceback (most recent call last):
File "<pyshell#122>", line 1, in <module>
a[1,3]
IndexError: index 3 is out of bounds for axis 1 with size 3

>>> a[1,0]
0

>>> a[0,0]
0

>>>

Accessing the column values from the matrix. we can use ellipsis(…) to get the column or row values in particular. If we place the ellipsis in the row position, it will get you the all the values of particular column.

>>> a[...,1]
array([0, 1, 0])

>>> a[...,0]
array([0, 0, 0])

>>> a[...,2]
array([0, 0, 2])

Accessing the row values from diagonal matrix. If we place the ellipsis in the column value position, it will get you the all the values of particular row mentioned.

>>> a[1]
array([0, 1, 0])

>>> a[1,...]
array([0, 1, 0])

>>>

slicing:

>>> a=np.arange(20)

>>> a
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19])

>>> a[5:20:5]
array([ 5, 10, 15])

>>> a[:4]
array([0, 1, 2, 3])

>>> a[:10]
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

>>> a[1:5]
array([1, 2, 3, 4])

>>> a[5:]
array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])

>>> a[::5]
array([ 0, 5, 10, 15])

>>> a[0]
0

>>> a[1:5]
array([1, 2, 3, 4])