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.
The roll method takes three arguments:
The array you want to roll.
The number of positions to roll the array by.
The axis along which to roll the array.
To swap the rows in a NumPy array, you would use the following syntax:
np.roll(array_name, number_of_positions, axis=0)
Where array_name is the name of the NumPy array, number_of_positions is the number of rows you want to swap, and axis=0 tells the roll method to roll the array along the rows.
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.