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.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Arrays

  • NumPy Value Counts in Python
  • NumPy Get Number of Rows in Python