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

For more Practice: Solve these Related Problems:

  • Write a NumPy program to slice a 2D array and extract its last two columns using negative indexing.
  • Create a function that returns the last two columns of any given 2D array regardless of its shape.
  • Test the slicing on arrays with varying numbers of columns to ensure robust extraction of the final two.
  • Implement an alternative approach using np.take to retrieve the last two columns of an array.

Go to:


PREV : Calculate Euclidean Distance
NEXT : Read CSV and Store in Array


Python-Numpy Code Editor:

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.