w3resource

NumPy: Extract all the elements of the second row from a given (4x4) array


Extract Second Row of 4x4 Array

Write a NumPy program to extract all the elements of the second row from a given (4x4) array.

Pictorial Presentation:

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

# Printing the second row of the 'arra_data' array using row indexing
print(arra_data[1, :])

Sample Output:

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

Extracted data: Second row
[4 5 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[1, :]): Here print() function prints the second row of the array arra_data. In this case, it will print [4, 5, 6, 7]. The index 1 corresponds to the second row in the array, and the colon : indicates that all columns should be included.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to slice out the second row from a 4x4 array and print the result.
  • Create a function that extracts a specified row from a 2D array and validates the output.
  • Test the extraction on various arrays to ensure that the correct row is always returned.
  • Implement a solution using np.take along axis 0 to obtain the second row and compare it with slicing.

Go to:


PREV : Extract First Row of 4x4 Array
NEXT : Extract Third Column of 4x4 Array


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.