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

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

by Erma Khan

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: How to Swap Two Rows in a NumPy Array

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.

Additional Resources

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

How to Remove Duplicate Elements in NumPy Array
How to Replace Elements in NumPy Array
How to Rank Items in NumPy Array

Related Posts