NumPy: Find the index of the sliced elements as follows from a given 4x4 array
NumPy: Array Object Exercise-122 with Solution
Index of Sliced Elements in Array
Write a NumPy program to find the index of the sliced elements from a given 4x4 array.
Pictorial Presentation:
Sample Solution:
Python Code:
# Importing the NumPy library and aliasing it as 'np'
import numpy as np
# Creating a 4x4 array 'x' with elements from 0 to 15 using np.arange() and reshaping it to a 4x4 array
x = np.reshape(np.arange(16), (4, 4))
# Printing a message indicating the original array will be displayed
print("Original array:")
# Displaying the original array 'x'
print(x)
# Printing a message indicating the sliced elements will be displayed
print("Sliced elements:")
# Slicing specific elements from 'x' using advanced indexing with specific row and column indices
# The selected elements are x[0, 0], x[1, 1], x[2, 3]
result = x[[0, 1, 2], [0, 1, 3]]
# Displaying the sliced elements
print(result)
Sample Output:
Original arrays: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] Sliced elements: [ 0 5 11]
Explanation:
x = np.reshape(np.arange(16), (4, 4)): Create a 1D NumPy array of integers from 0 to 15 using np.arange(16), and then reshape it into a 4x4 2D array using np.reshape(). The array x looks like:
result = x[[0, 1, 2], [0, 1, 3]]: Use integer array indexing to select specific elements from the 2D array x. This line of code selects the elements with the following indices: (0, 0), (1, 1), and (2, 3). Integer array indexing allows you to select elements from different rows and columns by specifying their indices as lists or arrays.
print(result): Print the resulting 1D array of the selected elements:
Python-Numpy Code Editor:
Previous: Write a NumPy program to join a sequence of arrays along a new axis.
Next: Write a NumPy program to create two arrays when the size is bigger or smaller than a given array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-122.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics