We will learn together how to swap rows in a Numpy array.
It may happen that you might want to swap rows in your array. Luckily, it is very easy in the Numpy Python library.
How to swap rows in Numpy?
import numpy as np my_array = np.array([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]) print(f"My array: \n {my_array}") my_array[[0, 1]] = my_array[[1, 0]] print(f"My array with swapped rows: \n {my_array}")
I used my_array[[0, 1]] = my_array[[1, 0]] for a swap.
As you see, rows were swapped and nothing else changed.
How to swap rows using Numpy roll?
Another way to swap Numpy rows would be to use the Numpy roll method.
import numpy as np my_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) print(f"My array: \n {my_array}") my_array = np.roll(my_array,-1,axis=0) print(f"My array with swapped rows: \n {my_array}")
The output would be:
My array: [[ 1 2 3] [ 4 5 6] [ 7 8 9] [10 11 12]] My array with swapped rows: [[ 4 5 6] [ 7 8 9] [10 11 12] [ 1 2 3]]
This is important to use exactly np.roll(my_array,-1,axis=0) code. Without “axis=0” the output would be completely different.
My array: [[ 1 2 3] [ 4 5 6] [ 7 8 9] [10 11 12]] My array with swapped rows: [[ 2 3 4] [ 5 6 7] [ 8 9 10] [11 12 1]]
As you may notice, in such a situation, the values are moved instead of the rows swapped.