NumPy Array Indexing & Slicing

In this article, we will understand how the indexing and slicing works with NumPy Arrays in Python.

What is Indexing in NumPy?

Indexing in NumPy is a way to access single or multiple elements from a NumPy array. Each position in NumPy Array has a unique index, which you can use to access its value.

Select an element from a NumPy Array by Index

Suppose we have a NumPy array of integers, and we want to select the (i)th element from the array. Indexing in Python starts from 0. So,

  • The index position of the 1st element is 0.
  • The index position of the 2nd element is 1.
  • The index position of the 3rd element is 2.
  • The index position of the (i)th element is ((i-1)).

We can pass this index position to the [] subscript operator of the array, and it will give us the element at that index position. For example, to select the 5th element from a NumPy array, we need to pass index position 4.

import numpy as np

# Generate numbers from 100 to 110
arr = np.arange(100, 110)

print(arr)

You’ll get an array that looks like this:

[100 101 102 103 104 105 106 107 108 109]

In NumPy, indexing starts at 0. So, arr[0] would return 5, arr[1] would return 6, and so on. Here’s an example:

# Accessing 5th element i.e. at index 5
print(arr[5])  # Output: 105

# Accessing the first element i.e. at index 0
print(arr[0])  # Output: 100

Output:

105
100

Select Element at Invalid Index in NumPy Array

If you try to access an element at an index position that is out of bounds, like arr[22] in this case, you’ll get an error because we only have 10 elements, and the last valid index is 9. However, we are trying to access an element at index position 22, which is beyond the range of the array.

For example,

import numpy as np

# Generate numbers from 100 to 110
arr = np.arange(100, 110)

print(arr)

# Accessing element index 22
print(arr[22])

Error

    print(arr[22])
IndexError: index 22 is out of bounds for axis 0 with size 10

Negative Indexing in NumPy Array

Just like strings in Python, NumPy arrays also support negative indexing. So,

  • The index position of the last element in a NumPy array is -1.
  • The index position of the second-to-last element in a NumPy array is -2.
  • The index position of the third-to-last element in a NumPy array is -3.
  • The index position of the (i)th element from the end in a NumPy array is (-i).

We can pass this index position to the [] subscript operator of the array, and it will give us the element at that index position. Let’s see an example where we will select the last and second-to-last elements from a NumPy array.

import numpy as np

# Generate numbers from 100 to 110
arr = np.arange(100, 110)

print(arr) 

# Accessing the last element with negative indexing
print(arr[-1])  # Output: 109

# Accessing the second last element
print(arr[-2])  # Output: 108

Output:

[100 101 102 103 104 105 106 107 108 109]
109
108

What is Slicing in NumPy Array?

In Python, slicing is a way to access a range of elements from a NumPy Array.

Using Slicing to Select Range of Elements from NumPy Array

If you want to extract elements from index position 4 to 8, then you will pass these index positions separated by colon in the sbusctip operator of numpy array like this,

import numpy as np

# Generate numbers from 100 to 110
arr = np.arange(100, 110)

print(arr) 

# Slicing from index 4 to 8 (End index position will not be included)
print(arr[ 4 : 8 ])  # Output: [104 105 106 107]

Output:

[100 101 102 103 104 105 106 107 108 109]
[104 105 106 107]

Important Point: The upper limit is exclusive, so arr[4:8] includes the element at index 4 but not at index 8.

Using Slicing to Select Range of elements by Negative Indexing

We can slice a portion of the Numpy Array i.e. select multiple elements from a Numpy array using negative indices. In the below example, we will select last 4 elements from numpy array.

import numpy as np

# Generate numbers from 100 to 110
arr = np.arange(100, 110)

print(arr) 

# Slice the numpy array to select last 4 elements
print(arr[-5:-1])

Output:

[100 101 102 103 104 105 106 107 108 109]
[105 106 107 108]

Slicing till the End of a NumPy Array

In NumPy, if you want to select a range of elements from a specific index to the end of the array, you can do so by omitting the upper bound in the slice notation. Here’s an expanded version of your first example:

import numpy as np

# Generate numbers from 100 to 109
arr = np.arange(100, 110)
print(arr)

# Slicing from index 4 to the end of the array
sliced_array = arr[4:]
print(sliced_array)  # Output: [104 105 106 107 108 109]

Output:

[100 101 102 103 104 105 106 107 108 109]
[104 105 106 107 108 109]

Explanation:
arr[4:] tells Python to get all elements from the 4th index to the end of the array.
– Note that NumPy indexing starts at 0, so the 4th index actually corresponds to the 5th element in the array.

Now, let’s modify this example slightly to demonstrate a common use case:

# Slicing from index 6 to the end of the array
print(arr[6:])

Output:

[106 107 108 109]

Here, arr[6:] retrieves all elements from the 7th element to the end.

Slicing from the Beginning up to a Certain Index

To get elements from the start of the array up to, but not including, a certain index, you can omit the lower bound:

import numpy as np

# Generate numbers from 100 to 109
arr = np.arange(100, 110)
print(arr)

# Slicing from the start of the array
# up to (but not including) index 4
print(arr[:4])

Output:

[100 101 102 103 104 105 106 107 108 109]
[100 101 102 103]

Explanation:
arr[:4] retrieves elements from the beginning of the array up to (but not including) the element at index 4.

As an example, if you want to get the first three elements:

# Slicing the first 3 elements
print(arr[:3])

Output:

[100 101 102]

Copying the Entire Array with Slicing

Finally, if you omit both the lower and upper bounds in the slice, you get a copy of the entire array:

import numpy as np

# Generate numbers from 100 to 109
arr = np.arange(100, 110)
print(arr)

# Copying the entire array
arr2 = arr[:]

print(arr2) 

Output:

[100 101 102 103 104 105 106 107 108 109]
[100 101 102 103 104 105 106 107 108 109]

Explanation:
arr[:] effectively makes a new array that is a copy of arr.

This technique is often used to create a copy of the array that won’t affect the original array when modified.

Summary

In this lesson, we’ve learned to work with one-dimensional arrays in NumPy through indexing and slicing. We’ve learned that arrays are zero-indexed, how to access individual elements, and how to extract a range of elements with slicing.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top