Cross-Indexing a 2D NumPy array using np.ix_
NumPy: Advanced Indexing Exercise-9 with Solution
Indexing with np.ix_:
Write a NumPy program that creates two 1D NumPy arrays and uses np.ix_ to perform cross-indexing on a 2D array.
Sample Solution:
Python Code:
import numpy as np
# Create a 2D NumPy array of shape (5, 5) with random integers
array_2d = np.random.randint(0, 100, size=(5, 5))
# Create two 1D NumPy arrays for cross-indexing
row_indices = np.array([1, 3])
col_indices = np.array([0, 2, 4])
# Use np.ix_ to create an open mesh from the row and column indices
index_grid = np.ix_(row_indices, col_indices)
# Use the index grid to select elements from the 2D array
selected_elements = array_2d[index_grid]
# Print the original array and the selected elements
print('Original 2D array:\n', array_2d)
print('Row indices:\n', row_indices)
print('Column indices:\n', col_indices)
print('Selected elements using np.ix_:\n', selected_elements)
Output:
Original 2D array: [[72 26 99 42 96] [81 71 47 32 10] [19 91 70 19 60] [12 15 94 30 31] [65 87 10 20 98]] Row indices: [1 3] Column indices: [0 2 4] Selected elements using np.ix_: [[81 47 10] [12 94 31]]
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 (5, 5).
- Create 1D NumPy Arrays:
- Created two 1D NumPy arrays named row_indices and col_indices to specify the rows and columns for cross-indexing.
- Use np.ix_ for Cross-Indexing:
- Used np.ix_ to create an open mesh from the row and column indices. This creates a grid that can be used for cross-indexing.
- Select Elements Using Index Grid:
- Use the index grid created by np.ix_ to select elements from the 2D array.
- Print Results:
- Print the original 2D array, the row and column indices, and the selected elements to verify the indexing operation.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Index and select elements in 2D NumPy Array using Tuple of arrays.
Next: Replace elements in 2D NumPy array using Boolean Indexing.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/numpy/cross-indexing-a-2d-numpy-array-using-np-dot-ix_.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics