w3resource

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


Extract Third & Fourth Elements of First Two Rows

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

Pictorial Presentation:

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

# Using slicing to extract the first two rows and columns 2 and 3 (2:4 refers to 2nd and 3rd indices)
print(arra_data[0:2, 2:4])

Sample Output:

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

Extracted data: Third and fourth elements of the first and second rows 
[[2 3]
 [6 7]]

Explanation:

In the above code -

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[0:2, 2:4]): It prints a subarray of ‘arra_data’ containing the first two rows and the last two columns. The slicing syntax 0:2 indicates elements from index 0 (inclusive) to index 2 (exclusive), and the slicing syntax 2:4 indicates elements from index 2 (inclusive) to index 4 (exclusive).


For more Practice: Solve these Related Problems:

  • Write a NumPy program to extract the third and fourth elements of the first two rows from a 4x4 array using slicing.
  • Create a function that returns a specific submatrix from a given 2D array based on column ranges.
  • Test the extraction on multiple arrays to verify the correct columns are selected for the specified rows.
  • Implement an alternative method using np.ix_ to extract the desired sub-array and compare results.

Go to:


PREV : Extract First & Second Elements of First Two Rows
NEXT : Extract First & Third Elements of First/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.