How to Get Specific Column from NumPy Array (With Examples)


You can use the following syntax to get a specific column from a NumPy array:

#get column in index position 2 from NumPy array
my_array[:, 2]

The following examples shows how to use this syntax in practice.

Example 1: Get One Column from NumPy Array

The following code shows how to get one specific column from a NumPy array:

import numpy as np

#create NumPy array
data = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

#view NumPy array
data

array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

#get column in index position 2
data[:, 2]

array([ 3,  7, 11])

If you’d like to get a column from a NumPy array and retrieve it as a column vector, you can use the following syntax:

#get column in index position 2 (as a column vector)
data[:, [2]]

array([[ 3],
       [ 7],
       [11]])

Example 2: Get Multiple Columns from NumPy Array

The following code shows how to get multiple columns from a NumPy array:

import numpy as np

#create NumPy array
data = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

#view NumPy array
data

array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

#get columns in index positions 1 and 3 from NumPy array
data[:, [1,3]]

array([[ 2,  4],
       [ 6,  8],
       [10, 12]])

Example 3: Get Columns in Range from NumPy Array

The following code shows how to get columns in a range from a NumPy array:

import numpy as np

#create NumPy array
data = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

#view NumPy array
data

array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

#get columns in index positions 0 through 3 (not including 3)
data[:, 0:3]

array([[ 1,  2,  3],
       [ 5,  6,  7],
       [ 9, 10, 11]])

Note that the last value in the range (in this case, 3) is not included in the range of columns that is returned.

Additional Resources

The following tutorials explain how to perform other common operations in NumPy:

How to Map a Function Over a NumPy Array
How to Add a Column to a NumPy Array

Leave a Reply

Your email address will not be published.