w3resource

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


8. 2D Array & Tuple of Arrays Indexing

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.

For more Practice: Solve these Related Problems:

  • Create a 2D array and use a tuple of index arrays to select elements at positions (0,1), (1,2), and (2,0).
  • Write a function that returns a diagonal subarray from a 2D array using a tuple of indices.
  • Implement a solution that uses a tuple of arrays to swap non-adjacent elements in a 2D array.
  • Use tuple indexing to extract a checkerboard pattern from a 2D array.

Go to:


Previous: Boolean Indexing on 3D NumPy arrays with conditions.
Next: Cross-Indexing a 2D NumPy array using np.ix_.

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.



Follow us on Facebook and Twitter for latest update.