w3resource

NumPy: Find the index of the sliced elements as follows from a given 4x4 array


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:

NumPy: Find the index of the sliced elements as follows from a given 4x4 array

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:


For more Practice: Solve these Related Problems:

  • Write a NumPy program to slice a 4x4 array and then return the flat indices of the sliced elements.
  • Create a function that computes the original indices of elements obtained after slicing a multi-dimensional array.
  • Test the indexing function on different slices to ensure it accurately reflects the position in the original array.
  • Implement a solution that uses np.ravel_multi_index to convert multi-dimensional indices to flat indices.

Go to:


PREV : Join Arrays Along New Axis
NEXT : Resize Array to Bigger and Smaller Sizes


Python-Numpy Code Editor:

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

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.