w3resource

Index and select elements in 2D NumPy Array using Tuple of arrays

NumPy: Advanced Indexing Exercise-8 with Solution

Indexing with a Tuple of Arrays:

Write a NumPy program that creates a 2D NumPy array and uses a tuple of arrays to index and select a specific set of elements.

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))

# Define row and column indices as a tuple of arrays
row_indices = np.array([0, 1, 2, 3])
col_indices = np.array([4, 3, 2, 1])

# Use the tuple of arrays to index and select specific elements
selected_elements = array_2d[row_indices, col_indices]

# 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:\n', selected_elements)

Output:

Original 2D array:
 [[ 7 74 80 19  2]
 [63 29 42  4 36]
 [94 37 96 21 90]
 [28 81 62  7 66]
 [13  3 60 40 89]]
Row indices:
 [0 1 2 3]
Column indices:
 [4 3 2 1]
Selected elements:
 [ 2  4 96 81]

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).
  • Define Row and Column Indices:
    • Defined row_indices and col_indices arrays to specify the rows and columns from which to select elements.
  • Tuple of Arrays Indexing:
    • Used a tuple of arrays (row_indices, col_indices) to index and select specific elements from array_2d.
  • 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: Boolean Indexing on 3D NumPy arrays with conditions.
Next: Cross-Indexing a 2D NumPy array using np.ix_.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/index-and-select-elements-in-2d-numpy-array-using-tuple-of-arrays.php