w3resource

Select elements from 1D NumPy array using integer Indexing

NumPy: Advanced Indexing Exercise-2 with Solution

Integer Array Indexing:

Write a NumPy program that creates a 1D NumPy array and uses integer array indexing to select a subset of elements based on an index array.

Sample Solution:

Python Code:

import numpy as np

# Create a 1D NumPy array
array_1d = np.array([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])

# Define an index array to select specific elements
index_array = np.array([0, 2, 4, 6, 8])

# Use integer array indexing to select elements
selected_elements = array_1d[index_array]

# Print the original array and the selected elements
print('Original 1D array:\n', array_1d)
print('Index array:\n', index_array)
print('Selected elements:\n', selected_elements)

Output:

Original 1D array:
 [ 10  20  30  40  50  60  70  80  90 100]
Index array:
 [0 2 4 6 8]
Selected elements:
 [10 30 50 70 90]

Explanation:

  • Import libraries:
    • Imported numpy as np for array creation and manipulation.
  • Create 1D NumPy Array:
    • Create a 1D NumPy array named array_1d with elements ranging from 10 to 100.
  • Define Index Array:
    • Define an index array index_array containing specific indices to select elements from array_1d.
  • Integer Array Indexing:
    • Used integer array indexing to select elements from array_1d based on index_array.
  • Print Results:
    • Finally print the original 1D array, the index array, 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 using Boolean indexing.
Next: Select elements from 3D NumPy array using Fancy indexing.

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-1d-numpy-array-using-integer-indexing.php