w3resource

NumPy: Extract first element of the second row and fourth element of fourth row from a given (4x4) array


Extract First Element of Second Row & Fourth of Fourth Row

Write a NumPy program to extract the first element of the second row and the fourth element of the fourth row from a given (4x4) array.

Pictorial Presentation:

NumPy: Extract first element of the second row and fourth element of fourth row from a given (4x4) array

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'arra_data' containing integers from 0 to 15 and reshaping it into a 4x4 matrix
arra_data = np.arange(0, 16).reshape((4, 4))

# Displaying a message indicating the original array will be printed
print("Original array:")

# Printing the original 4x4 array 'arra_data'
print(arra_data)

# Displaying a message indicating the extracted data (First element of the second row and fourth element of fourth row)
print("\nExtracted data: First element of the second row and fourth element of fourth row")

# Using fancy indexing to extract elements from specific rows and columns using their indices
print(arra_data[[1, 3], [0, 3]]) 

Sample Output:

Original array:
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]

Extracted data: First element of the second row and fourth element of fourth row  
[ 4 15]

Explanation:

In the above exercise –

arra_data = np.arange(0, 16).reshape((4, 4)): It creates a 1-dimensional NumPy array with elements from 0 to 15 (excluding 16) using np.arange(0, 16) and then reshapes it into a 2-dimensional array with 4 rows and 4 columns using .reshape((4, 4)).

print(arra_data[[1, 3], [0, 3]]): This line prints specific elements of arra_data by selecting elements with row indices 1 and 3 and column indices 0 and 3. The indexing [1, 3] selects the second and fourth rows, and [0, 3] selects the first and fourth columns. The elements at the intersection of these rows and columns are extracted and create a subarray.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to extract the first element of the second row and the fourth element of the fourth row from a 4x4 array using explicit indexing.
  • Create a function that retrieves specific elements from given row-column pairs and returns them as a 1D array.
  • Test the extraction with various index pairs to ensure that the function correctly identifies the target elements.
  • Implement a solution that uses np.array indexing with a list of index tuples and compare it with manual extraction.

Go to:


PREV : Extract First & Fourth Columns
NEXT : Extract Second & Third Elements of Second & Third Rows


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.