Select elements from 1D NumPy array using integer Indexing
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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics