w3resource

Select elements from 2D NumPy array using integer Indexing

NumPy: Advanced Indexing Exercise-6 with Solution

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.

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.



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://w3resource.com/python-exercises/numpy/select-elements-from-2d-numpy-array-using-integer-indexing.php