Ask Your Question

Revision history [back]

To extract a specific portion from a ndarray using advanced indexing in NumPy, you can use square brackets to create a Boolean or integer array that corresponds to the elements you want to extract, and then pass that array inside another set of square brackets along with the original ndarray.

For example, to extract a specific rectangle of elements from a 2D ndarray arr, you can define a Boolean array mask that indicates which rows and columns of arr to extract, and then use that mask inside a set of square brackets to extract the corresponding elements:

import numpy as np

# Define the ndarray and the mask
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
mask = np.array([[True, False, True], [False, True, False]])

# Use the mask to extract the specific elements
subset = arr[mask]

# Print the result
print(subset)  # Output: [1 3 5]

In this example, the mask [[True, False, True], [False, True, False]] indicates to extract the elements corresponding to the first and third columns of arr, and the second row. This results in a 1D ndarray containing the values [1, 3, 5].

Alternatively, you can use integer arrays to specify the indices of the elements you want to extract. For example, to extract the same subset of elements as above using integer arrays, you can define two arrays rows and cols that contain the indices of the rows and columns to extract, and use those arrays inside the square brackets:

import numpy as np

# Define the ndarray and the index arrays
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
rows = np.array([0, 1, 1])
cols = np.array([0, 1, 2])

# Use the index arrays to extract the specific elements
subset = arr[rows, cols]

# Print the result
print(subset)  # Output: [1 5 6]

In this example, the index arrays [0, 1, 1] and [0, 1, 2] indicate to extract the elements corresponding to the first row and column, the second row and second column, and the second row and third column. This results in a 1D ndarray containing the values [1, 5, 6].