NumPy: Access last two columns of a multidimensional columns
NumPy: Array Object Exercise-104 with Solution
Write a NumPy program to access the last two columns of a multidimensional column.
Sample Solution:
Python Code:
# Importing the NumPy library and aliasing it as 'np'
import numpy as np
# Creating a NumPy array 'arra' with nested lists as elements
arra = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Printing the original array 'arra'
print(arra)
# Extracting specific columns (index 1 and index 2) using numpy array slicing
# ':' indicates all rows, '[1,2]' indicates columns at indices 1 and 2
result = arra[:, [1, 2]]
# Printing the extracted columns from the original array 'arra'
print(result)
Sample Output:
[[1 2 3] [4 5 6] [7 8 9]] [[2 3] [5 6] [8 9]]
Explanation:
In the above code –
arra = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]): This line creates a 3x3 NumPy array and stores in the variable ‘arra’ with values from 1 to 9.
result = arra[:, [1, 2]]: Select all rows (indicated by the colon :) and columns with indices 1 and 2 (the second and third columns) from the array arra. The notation [:, [1, 2]] means that we are selecting all rows and the columns with indices specified in the list [1, 2].
Finally print() function prints the resulting array.
Pictorial Presentation:
Python-Numpy Code Editor:
Previous: Write a NumPy program to calculate the Euclidean distance.
Next: Write a NumPy program to read a CSV data file and store records in an 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://w3resource.com/python-exercises/numpy/python-numpy-exercise-104.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics