w3resource

NumPy: Access last two columns of a multidimensional columns


Access Last Two Columns of 2D Array

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: Access last two columns of a multidimensional columns

Python-Numpy Code Editor: