w3resource

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


Extract Second & Third Columns

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

Pictorial Presentation:

NumPy: Extract all the elements of the second and third columns 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 (all the elements of the second and third columns)
print("\nExtracted data: All the elements of the second and third columns")

# Using slicing to extract all rows and specific columns (2nd and 3rd columns) from 'arra_data'
print(arra_data[:, [1, 2]])

Sample Output:

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

Extracted data: All the elements of the second and third columns
[[ 1  2]
 [ 5  6]
 [ 9 10]
 [13 14]]

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, 2]]): This line prints specific columns of ‘arra_data’ by selecting all rows (indicated by :) and only the columns with indices 1 and 2 (indicated by [1, 2]).


For more Practice: Solve these Related Problems:

  • Write a NumPy program to slice out the second and third columns from a 4x4 array using column indexing.
  • Create a function that returns a sub-array containing only the specified columns of any 2D array.
  • Test the extraction using both negative indexing and np.take to validate the correct columns are retrieved.
  • Implement a solution that verifies the consistency of the output by comparing with a manually built sub-array.

Go to:


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