Select Rectangular Subarray using advanced slicing in NumPy
14. 2D Array Slicing with Index Arrays for Subarray
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:
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.
For more Practice: Solve these Related Problems:
- Create a 2D array and use slicing combined with an index array to extract a central rectangular subarray.
- Write a function that takes a 2D array and returns a subarray defined by specific start and end indices for rows and columns.
- Implement a solution that slices a 2D array to obtain corner subarrays (top-left, top-right, etc.) using index arrays.
- Test the slicing method on arrays with even and odd dimensions to ensure the subarray is correctly extracted.
Go to:
Previous: Select elements using Boolean Indexing with logical operators.
Next: Set elements in 3D NumPy array using Boolean Indexing.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.