NumPy Slicing and Indexing

NumPyNumPyBeginner
Practice Now

Introduction

NumPy is a popular Python library used for scientific computing. It provides high-performance array operations and mathematical functions that are useful for numerical data analysis. In this lab, you will learn NumPy's slicing and indexing features.

Slicing Arrays

Slicing is the process of extracting a subset of an array by specifying a range of indices. NumPy arrays can be sliced using the colon : operator.

Open the Python Shell

Open the Python shell by typing the following command in the terminal.

python3

Import NumPy

NumPy is already installed, you can import it in your Python code:

import numpy as np

Slice Arrays in One Dimension

## create a 1-dimensional array
a = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

## slice the array from index 2 to index 5
print(a[2:5])

Output:

[2 3 4]

Slice Arrays in Multiple Dimensions

You can also slice arrays in multiple dimensions.

## create a 2-dimensional array
b = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])

## slice the first two rows and first two columns
print(b[:2, :2])

Output:

[[0 1]
 [3 4]]

Indexing with Boolean Arrays

Boolean indexing is a powerful feature that allows us to filter an array based on a condition. You can create a boolean array by applying a logical operator to an existing array.

Create a 1-dimensional Array

c = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

Create a Boolean Array Based on the Condition (c > 5)

mask = c > 5
print(mask)

Output:

[False False False False False False  True  True  True  True]

Filter the Original Array Using the Boolean Array

print(c[mask])

Output:

[6 7 8 9]

Fancy Indexing

Fancy indexing is a way of indexing an array using an array of indices. You can use this technique to extract specific elements or subsets of an array.

## create a 1-dimensional array
d = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

## create an array of indices
indices = np.array([1, 3, 5])

## use fancy indexing to extract the elements at the specified indices
print(d[indices])

Output:

[1 3 5]
  • You can also use fancy indexing to assign values to specific elements in an array.
## create a 1-dimensional array
e = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

## create an array of indices
indices = np.array([1, 3, 5])

## assign the value 10 to the elements at the specified indices
e[indices] = 10
print(e)

Output:

[ 0 10  2 10  4 10  6  7  8  9]

Summary

Congratulations! You have completed the NumPy Slicing and Indexing Lab.

In this lab, you covered the basics of slicing and indexing NumPy arrays:

  • Slicing allows you to extract a subset of an array by specifying a range of indices.
  • Boolean indexing allows you to filter an array based on a condition.
  • Fancy indexing allows you to extract specific elements or subsets of an array by using an array of indices.

Other NumPy Tutorials you may like