How to Swap Two Columns in a NumPy Array (With Example)?

Swapping two columns in a NumPy array is relatively easy and can be done with the transpose method. This method switches the rows and columns of the array, and can be used to swap two columns by swapping the order of two columns in the array prior to the transpose. To illustrate this concept, say we have an array with 4 rows and 3 columns. Swapping the second and third columns can be done by first rearranging the array so that the second and third columns are switched, then transposing it. The resulting array will have the second and third columns swapped from the original.


You can use the following basic syntax to swap two columns in a NumPy array:

some_array[:, [0, 2]] = some_array[:, [2, 0]]

This particular example will swap the first and third columns in the NumPy array called some_array.

All other columns will remain in their original positions.

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

Related:

Example: Swap Two Columns in NumPy Array

Suppose we have the following NumPy array:

import numpy as np

#create NumPy array
some_array = np.array([[1, 1, 2], [3, 3, 7], [4, 3, 1], [9, 9, 5], [6, 7, 7]])

#view NumPy array
print(some_array)

[[1 1 2]
 [3 3 7]
 [4 3 1]
 [9 9 5]
 [6 7 7]]

We can use the following syntax to swap the first and third columns in the NumPy array:

#swap columns 1 and 3
some_array[:, [0, 2]] = some_array[:, [2, 0]]

#view updated NumPy array
print(some_array)

[[2 1 1]
 [7 3 3]
 [1 3 4]
 [5 9 9]
 [7 7 6]]

Notice that the first and third columns have been swapped.

All other columns remained in their original positions.

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

x