Table of Contents
Swapping two columns in a NumPy array refers to rearranging the order of two columns within the array. This can be achieved by using the built-in function “np.swapaxes()” which takes in the array and the indices of the columns to be swapped as parameters. An example of this would be using “np.swapaxes(arr, 1, 2)” where “arr” is the name of the array and 1 and 2 are the indices of the columns to be swapped. This function will return a new array with the two columns swapped.
Swap Two Columns in a NumPy Array (With Example)
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:
Cite this article
stats writer (2024). How can I swap two columns in a NumPy array? Can you provide an example?. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-can-i-swap-two-columns-in-a-numpy-array-can-you-provide-an-example/
stats writer. "How can I swap two columns in a NumPy array? Can you provide an example?." PSYCHOLOGICAL SCALES, 25 Jun. 2024, https://scales.arabpsychology.com/stats/how-can-i-swap-two-columns-in-a-numpy-array-can-you-provide-an-example/.
stats writer. "How can I swap two columns in a NumPy array? Can you provide an example?." PSYCHOLOGICAL SCALES, 2024. https://scales.arabpsychology.com/stats/how-can-i-swap-two-columns-in-a-numpy-array-can-you-provide-an-example/.
stats writer (2024) 'How can I swap two columns in a NumPy array? Can you provide an example?', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-can-i-swap-two-columns-in-a-numpy-array-can-you-provide-an-example/.
[1] stats writer, "How can I swap two columns in a NumPy array? Can you provide an example?," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, June, 2024.
stats writer. How can I swap two columns in a NumPy array? Can you provide an example?. PSYCHOLOGICAL SCALES. 2024;vol(issue):pages.
