w3resource

NumPy: Extract second and fourth elements of the second and fourth rows from a given (4x4) array


Extract Second & Fourth Elements of Second/Fourth Rows

Write a NumPy program to extract the second and fourth elements of the second and fourth rows from a given (4x4) array.

Pictorial Presentation:

NumPy: Extract second and fourth elements of the second and fourth rows 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 (second and fourth elements of the second and fourth rows)
print("\nExtracted data: Second and fourth elements of the second and fourth rows")

# Using slicing to extract the second and fourth elements of every other row and column starting from the second row and second column
print(arra_data[1::2, 1::2]) 

Sample Output:

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

Extracted data: Second and fourth elements of the second and fourth rows 
[[ 5  7]
 [13 15]]

Explanation:

. In the above example -

arra_data = np.arange(0, 16).reshape((4, 4)): This line 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::2, 1::2]): It prints specific elements of ‘arra_data’ by selecting every second row starting from the second row (index 1) and every second column starting from the second column (index 1) using the slicing syntax 1::2.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to extract the second and fourth elements from the second and fourth rows of a 4x4 array.
  • Create a function that uses boolean masking to select specific elements from chosen rows.
  • Test the extraction with different arrays to ensure that the correct elements are consistently retrieved.
  • Implement an alternative approach using np.ix_ to form the index arrays and compare outputs.

Go to:


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


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.