codingstreets
Search
Close this search box.

Introduction to Python Numpy Indexing

In This Article You Will Learn About Python Numpy Indexing.

Python NumPy Indexing – Before moving ahead, let’s know a little bit about Python Numpy Arrays

Access Array Elements

Accessing an array element is possible by indexing it.

An array element can be accessed by using its index number.

NumPy array indexes begin with 0. This means that the index of the first element has index 0, while the index of the second element has index 1, etc.

Example – Taking out the first element from the array.

import numpy as np
Array = np.array([11, 12, 13, 14])

print(Array[0])
Output - 

11

As a result, it returned element 11 of index number 0.

Example – Taking out the second element from the array.

import numpy as np
Array = np.array([11, 12, 13, 14])

print(Array[1])
Output - 

12

In the final analysis, it returned the second element from the array.

Note: Index number starts from 0.

Example – Taking out the third and fourth elements from the array and later subtracting them.

import numpy as np
Array = np.array([11, 12, 13, 14])

print(Array[2] - Array[3])
Output - 

13-14 = -1 

Hence, it returned Example – Taking out the third and fourth elements from the array after subtracting them.

Access 2-D Arrays

You can access elements from 2-D arrays using comma-separated integers. These represent the dimension and index of the element.

Example – Accessing the 3rd element in 1st dim:

import numpy as np
Array = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('3rd element on 1st dim: ', Array[0, 2])
Output - 

3rd element on 1st dim:  8

Thus, it returned 3rd element from the range in 1st dim.

Example – Accessing the 2nd element in 2nd dim:

import numpy as np
Array = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('2nd element on 2nd dim: ', Array[0, 1])
Output - 

2nd element on 2nd dim: 7

Accordingly, it returned the 2nd element on the 2nd dim from the range.

Access 3-D Arrays

To access elements from 3-D arrays we can use comma-separated integers representing the dimensions and the index of the element.

Example – Accessing the 2nd element of the second array of the second array.

import numpy as np
Array = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10,11,12]]])

print (Array [1, 1, 1])
Python NumPy Indexing

Hence, it returned 2nd element of the second array of the second array.

Negative Indexing

To access an array at the end, use negative indexing.

Example – Get the last element from the 2nd dim:

import numpy as np
Array = np.array([[1,2,3,4], [6,7,8,9]])

print('Last element from 2nd dim: ', Array[1, -1])
Output -

Last element from 2nd dim:  9 

As a result, it returned the last element from the 2nd dim.

If you find anything incorrect in the above-discussed topic and have any further questions, please comment below.

Like us on

Recent Post

Popular Post

Top Articles

Archives
Categories

Share on