NumPy: Extract all the elements of the first and fourth columns from a given (4x4) array
NumPy: Array Object Exercise-142 with Solution
Extract First & Fourth Columns
Write a NumPy program to extract all the elements of the first and fourth columns from a given (4x4) array.
Pictorial Presentation:
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 first and fourth columns)
print("\nExtracted data: All the elements of the first and fourth columns")
# Using slicing to extract all rows and specific columns (1st and 4th columns) from 'arra_data'
print(arra_data[:, [0, 3]])
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 first and fourth columns [[ 0 3] [ 4 7] [ 8 11] [12 15]]
Explanation:
In the above code -
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[:, [0, 3]]): This line prints specific columns of ‘arra_data’ by selecting all rows (indicated by :) and only the columns with indices 0 and 3 (indicated by [0, 3]).
Python-Numpy Code Editor:
Previous: Write a NumPy program to extract all the elements of the second and third columns from a given (4x4) array.
Next: Write a NumPy program to extract first element of the second row and fourth element of fourth row from a given (4x4) array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-142.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics