Let’s learn how to get a column in a Numpy array. This is what allows you to manipulate data in the Numpy Python library.

We have such a Numpy array:

[1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 1.10], [2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 2.10], [3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 3.10]

## How to get a single column?

How to get only the elements from the fourth column? Like that:

import numpy as np my_array = np.array(( [1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 1.10], [2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 2.10], [3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 3.10])) chosen_elements = my_array[:, 3] print(chosen_elements)

chosen_elements = my_array[:, 3] selects all elements from the fourth column (index 3, as indexing starts from 0 in Python).

## How to get one value from given column and row?

Keep moving further.

How to get elements from the second row and fourth column?

import numpy as np my_array = np.array(( [1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 1.10], [2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 2.10], [3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 3.10])) chosen_elements = my_array[1, 3] print(chosen_elements)

chosen_elements = my_array[1, 3] returned second row and fourth column.

## How to get multiple columns?

So, how do you get a lot of columns? Let’s get columns two through six.

import numpy as np my_array = np.array(( [1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 1.10], [2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 2.10], [3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 3.10])) chosen_elements = my_array[:, 1:6] print(chosen_elements)

chosen_elements = my_array[:, 1:6] is returning columns second to sixth thanks to colon. A colon denotes a range of 1 to 6 columns, 2 to 6.

## How to get every few columns

One more tip.

How to get many columns from a step? Let’s return to columns second to sixth, but every second column.

import numpy as np my_array = np.array(( [1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 1.10], [2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 2.10], [3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 3.10])) chosen_elements = my_array[:, 1:6:2] print(chosen_elements)

chosen_elements = my_array[:, 1:6:2] as you can notice added a step. Another colon is doing that, and digit 2 tells how big the step is.

Now, you can get columns in Numpy arrays.