NumPy

Indexing and Slicing

Basic indexing and slicing

This is an indexing and slicing tutorial.

NumPy is a powerful library for numerical computing in Python. It provides support for multidimensional arrays and various operations on them. Indexing and slicing in NumPy are fundamental operations used to access and manipulate elements within arrays. Understanding indexing and slicing is crucial for effectively working with NumPy arrays, especially when dealing with large datasets or complex computations.

Let’s explore each process separately.

Indexing

Indexing in NumPy arrays is similar to indexing in Python lists. You can access individual elements or slices of elements using square brackets “[ ]” Indexing in NumPy starts from 0.

import numpy as np

# Sample 1D array
arr = np.array([1, 2, 3, 4, 5])

# Accessing individual elements
print(arr[0])
print(arr[2])

# Negative indexing (starts from the end)
print(arr[-1])

# Output: 1
# Output: 3
# Output: 5

Slicing

Slicing allows you to access a portion of an array by specifying a range of indices. The syntax for slicing is [ start : stop : step ]. It returns a new array containing the specified elements.

1 dimensional arrays

import numpy as np

# Sample 1D array
arr = np.array([1, 2, 3, 4, 5])

# Slicing
print(arr[1:4])    
print(arr[:3])
print(arr[2:])
print(arr[::2])
[2 3 4]
[1 2 3] # (start is omitted, defaults to 0)
[3 4 5] # (stop is omitted, defaults to end)
[1 3 5] # (step by 2)

Multidimensional arrays

import numpy as np

# Sample 2D array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Slicing
print(arr[0, 1])
print(arr[:, 1])
print(arr[1:, :2])
# (row 0, column 1)
2
# (all rows, column 1)
[2 5 8]
# (rows 1 and 2, columns 0 and 1)
[[4 5] [7 8]]

Boolean indexing

Boolean indexing in NumPy allows you to select elements from an array based on conditions expressed as boolean arrays. It’s a powerful way to filter and manipulate data within arrays.

You can create a boolean array that has the same shape as the original array, where each element indicates whether the corresponding element in the original array satisfies a certain condition. Then, you can use this boolean array to select elements from the original array. You can also combine multiple conditions using logical operators like “&(and), “|(or), and “~(not).

Let’s work through practical examples.

1 dimensional arrays

import numpy as np

# Sample 1D array
arr = np.array([1, 2, 3, 4, 5])

# Boolean array based on condition
bool_arr = arr > 2

print(bool_arr)
# Output: [False False True True True]

We can now filter through the array based on the above. We do it by inputting the boolean array as an index of the original array.

# Using boolean array to index the original array
print(arr[bool_arr])
# Output: [3 4 5]

Let’s look at an example with multiple conditions.

import numpy as np

# Sample 1D array
arr = np.array([1, 2, 3, 4, 5])

# Boolean array based on multiple conditions
bool_arr = (arr > 2) & (arr < 5)

print(bool_arr)
# Output: [False False True True False]

Let’s filter through the array again.

# Using boolean array to index the original array
print(arr[bool_arr])
# Output: [3 4]

Multidimensional arrays

Boolean arrays must match the shape of the original array along all dimensions.

import numpy as np

# Sample 2D array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Boolean array based on condition
bool_arr = arr > 5

print(bool_arr)
# Output: [[False False False] [False False True] [True True True]]

Now filter the outcome.

# Using boolean array to index the original array
print(arr[bool_arr])
# Output: [6 7 8 9]

Fancy indexing

Fancy indexing in NumPy refers to accessing and modifying arrays using arrays of indices or Boolean arrays. It allows for more advanced and flexible indexing operations compared to basic indexing and slicing. Instead of inputting single number (scalar), this method uses arrays of indices for indexing.

Let’s see a practical example.

1 dimensional arrays

import numpy as np

# Sample 1D array
arr = np.array([1, 2, 3, 4, 5])

# Array of indices
indices = np.array([0, 2, 4])

# Fancy indexing to access elements
print(arr[indices])
# Output: [1 3 5]

Multidimensional arrays

import numpy as np

# Sample 2D array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Arrays of row and column indices
row_indices = np.array([0, 1, 2])
col_indices = np.array([0, 2, 1])

# Fancy indexing to access elements
print(arr[row_indices, col_indices])
# Output: [1 6 8]

Boolean arrays

import numpy as np

# Sample 1D array
arr = np.array([1, 2, 3, 4, 5])

# Boolean array
bool_arr = np.array([True, False, True, False, True])

# Boolean array for fancy indexing
print(arr[bool_arr])
# Output: [1 3 5]

This is an original indexing and slicing educational material created by aicorr.com.

Next: Broadcasting

by AICorr Team

We are proud to offer our extensive knowledge to you, for free. The AICorr Team puts a lot of effort in researching, testing, and writing the content within the platform (aicorr.com). We hope that you learn and progress forward.