Learn how to extract and manipulate columns in NumPy arrays using indexing and slicing techniques for efficient data manipulation in Python.

NumPy 2D arrays use axis indexing where axis 0 represents rows and axis 1 represents columns, enabling efficient column extraction and data selection.
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 Extract a Single Column from a NumPy Array Using Index Slicing
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)

The NumPy slicing syntax my_array[:, 3] selects all rows (:) and the fourth column (index 3), using zero-based indexing to extract a 1D column array.
How to Access a Single Element by Row and Column Index in NumPy Arrays
Let’s explore extracting specific values from multiple rows and columns.
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 Extract Multiple Columns from NumPy Arrays Using Range Slicing
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)

The NumPy slicing syntax my_array[:, 1:6] extracts columns at indices 1 through 5 (second to sixth columns), using Python’s colon notation for range selection across all rows.
How to Extract Columns with Step Intervals Using NumPy Array Slicing
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)

The NumPy slicing syntax my_array[:, 1:6:2] extracts columns 1 through 5 with a step of 2, returning every second column in the specified range using three-part slice notation.
Master NumPy column extraction using index slicing, range slicing, and step intervals for efficient data manipulation and array subsetting in Python.
