How to Get Column of NumPy Array

Muhammad Maisam Abbas Feb 02, 2024
How to Get Column of NumPy Array

This tutorial will introduce the method to get a specific column from a multi-dimensional NumPy array in Python.

Get Column From a Multi-Dimensional NumPy Array With the Basic Slicing Method

The basic slicing method works on the same principle as the list slicing in Python. We can use the basic slicing method to get a specific column from a multi-dimensional NumPy array. The basic slicing method creates a new view of our existing array instead of creating a new copy of the array. These new viewpoints at the existing array and the memory of the original array cannot be released until all the views pointing at the original array are collected by the Garbage Collector. The following code example shows us how to get a specific column from a multi-dimensional NumPy array with the basic slicing method in Python.

import numpy as np

array = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]])
print(array[:, 1])

Output:

[2 4 6 8 0]

In the above code, we extracted the second column of the multi-dimensional NumPy array array with the [:,1] slicing index in Python. The first portion of the index is the index of the rows. We have left the first portion blank because we want to select all the rows. The : operator represents a selecting operation in the index. We used the ,1 as the column index to get the second column from each row.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn