w3resource

Select Rectangular Subarray using advanced slicing in NumPy


NumPy: Advanced Indexing Exercise-14 with Solution


Advanced Slicing with Index Arrays:

Write a NumPy program that creates a 2D NumPy array and uses slicing in combination with index arrays to select a rectangular subarray.

Sample Solution:

Python Code:

import numpy as np

# Create a 2D NumPy array of shape (6, 6) with random integers
array_2d = np.random.randint(0, 100, size=(6, 6))

# Define the row and column indices to slice the array
row_indices = np.arange(2, 5)  # rows from index 2 to 4 (inclusive)
col_indices = np.arange(1, 4)  # columns from index 1 to 3 (inclusive)

# Use slicing in combination with index arrays to select a subarray
subarray = array_2d[row_indices[:, np.newaxis], col_indices]

# Print the original array and the selected subarray
print('Original 2D array:\n', array_2d)
print('Row indices:', row_indices)
print('Column indices:', col_indices)
print('Selected subarray:\n', subarray)

Output:

Original 2D array:
 [[85 43  7 40 45 20]
 [82 81 36 16 71 33]
 [82 70 86 55 10  0]
 [36 74 18 82 84 12]
 [91  3 67 18 60 19]
 [ 0 54 73 10 27  7]]
Row indices: [2 3 4]
Column indices: [1 2 3]
Selected subarray:
 [[70 86 55]
 [74 18 82]
 [ 3 67 18]]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Create 2D NumPy Array:
    • Create a 2D NumPy array named array_2d with random integers ranging from 0 to 99 and a shape of (6, 6).
  • Define Row and Column Indices:
    • Define row_indices to specify rows from index 2 to 4 (inclusive).
    • Define col_indices to specify columns from index 1 to 3 (inclusive).
  • Slicing with Index Arrays:
    • Used slicing in combination with index arrays to select a rectangular subarray from 'array_2d'.
  • Print Results:
    • Print the original 2D array, the row and column indices, and the selected subarray to verify the slicing operation.

Python-Numpy Code Editor: