w3resource

Select elements from 2D NumPy array using integer Indexing


6. 2D Array & Integer Indexing with Broadcasting

Integer Indexing with Broadcasting:

Write a NumPy program that creates a 2D NumPy array and uses integer indexing with broadcasting to select elements from specific rows and all columns.

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 the row indices to select specific rows
row_indices = np.array([1, 3])

# Use integer indexing with broadcasting to select elements from specific rows and all columns
selected_elements = array_2d[row_indices[:, np.newaxis], np.arange(array_2d.shape[1])]
# Print the original array and the selected elements
print('Original 2D array:\n', array_2d)
print('Selected rows:\n', row_indices)
print('Selected elements from specific rows and all columns:\n', selected_elements)

Output:

Original 2D array:
 [[29 88 36 92 36]
 [11 23  6 57 79]
 [55 24 17 29 82]
 [96 61 85 34 75]
 [67 61 86 34 37]]
Selected rows:
 [1 3]
Selected elements from specific rows and all columns:
 [[11 23  6 57 79]
 [96 61 85 34 75]]

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 indices:
    • Defined row_indices array to specify the rows from which to select elements.
  • Integer Indexing with Broadcasting:
    • Used integer indexing with broadcasting to select elements from the specified rows and all columns. This was done by combining row_indices with np.arange to select all columns.
  • Print Results:
    • Print the original 2D array, the row indices, and the selected elements to verify the indexing operation.

For more Practice: Solve these Related Problems:

  • Create a 2D array and use an integer index array along with broadcasting to select the first and last columns of each row.
  • Implement a function that uses integer indexing to extract elements from specific rows and then broadcast the selection to all columns.
  • Write a program that rearranges the columns of a 2D array based on an index array and uses broadcasting to fill missing values.
  • Use integer indexing combined with broadcasting to create a new array where each row is shifted by a different offset.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Select elements from 2D NumPy array with random floats using Boolean indexing.
Next: Boolean Indexing on 3D NumPy arrays with conditions.

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.