NumPy Accessing Arrays

In this tutorial you will learn:

  • Access NumPy Array
  • Accessing Arrays with Negative Index

Access NumPy Array

The elements of NumPy Array can be accessed by indexing, it’s very similar to accessing an element in an array. We already know that the index of an array start with zero.

Example

Access a 1-D array is very simple and straight forward we just need to pass the index in square brackets and print the value.

  1. import numpy as np
  2. arr = np.array([10, 8, 7, 2])
  3. print("** NumPy Show 1-D array access**”)
  4. print("Third element is: ", arr[2])

In order to access 2-D array using index we use the first index in square brackets to identify the first level array and second index in square brackets to identify the second level array.

  1. nparr1 = np.array([[9,5,6,7], [2,3,1,6]])
  2. print("\n\n** NumPy 2-D Array Access **")
  3. print("2nd Array's of Last Element", nparr1[1, 3])

For 3-D array we can use 3 indexes just as shown in the next example.

  1. nparr3 = np.array([[[3, 3, 3], [2, 8, 1]], [[5, 1, 3], [0, 31, 42]]])
  2. print("\n\n** NumPy 3-D Array Access **")
  3. print("2nd Element of first array then 1st element of second array\n and then print 2nd element of 3rd array", nparr3[1, 0, 1])

Accessing Arrays with Negative Index

Negative Indexes work from right to left and  the can also be used to access NumPy arrays. The index on the extreme right starts with -1. Let’s look at an example to see is how we can use the negative indexing.

  1. print("\n\n** Numpy Arra Access using negative indexing **")
  2. nparrNeg = np.array([[6,9,2,8,5], [1,22,44,55,0]])
  3. print("Second element from 1st Array: ", nparrNeg[-2, -4])

Add new comment