w3resource

NumPy: Extract first, third and fifth elements of the third and fifth rows from a given (6x6) array


Extract First, Third, Fifth Elements of Third/Fifth Rows of 6x6 Array

Write a NumPy program to extract the first, third and fifth elements of the third and fifth rows from a given (6x6) array.

Pictorial Presentation:

NumPy: Extract first, third and fifth elements of the third and fifth rows from a given (6x6) 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 35 and reshaping it into a 6x6 matrix
arra_data = np.arange(0, 36).reshape((6, 6))

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

# Printing the original 6x6 array 'arra_data'
print(arra_data)

# Displaying a message indicating the extracted data (First, third, and fifth elements of the third and fifth rows)
print("\nExtracted data: First, third, and fifth elements of the third and fifth rows")

# Using slicing to extract a sub-array containing the first, third, and fifth elements of the third and fifth rows
print(arra_data[2::2, ::2])

Sample Output:

Original array:
[[ 0  1  2  3  4  5]
 [ 6  7  8  9 10 11]
 [12 13 14 15 16 17]
 [18 19 20 21 22 23]
 [24 25 26 27 28 29]
 [30 31 32 33 34 35]]

Extracted data: First, third and fifth elements of the third and fifth rows
[[12 14 16]
 [24 26 28]]

Explanation:

In the above exercise -

arra_data = np.arange(0, 36).reshape((6, 6)): This line creates a 1-dimensional NumPy array with elements from 0 to 35 (excluding 36) using np.arange(0, 36) and then reshapes it into a 2-dimensional array with 6 rows and 6 columns using .reshape((6, 6)).

print(arra_data[2::2, ::2]): It prints a subarray of ‘arra_data’ by selecting rows starting from index 2 with a step of 2, and columns starting from index 0 with a step of 2 using slicing with a step.

The subarray consists of the elements at rows 2 and 4 and columns 0, 2, and 4 in the original array ‘arra_data’.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to extract non-consecutive elements (first, third, and fifth) from specified rows of a 6x6 array.
  • Create a function that uses advanced indexing to return selected elements from the third and fifth rows.
  • Test the extraction on a 6x6 array by comparing the output with manually calculated indices.
  • Implement a solution that uses np.take with a custom index array to extract the desired columns.

Go to:


PREV : Extract Second & Third Elements of Second & Third Rows
NEXT : Add Arrays A (3,3) and B (,3)


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.