How to swap rows in Numpy array?

We will learn together how to swap rows in a Numpy array.

Numpy array swap rows

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}")

To swap rows, the syntax my_array[[0, 1]] = my_array[[1, 0]] is utilized. This directly swaps the first row with the second.

See also  How to calculate sum of columns and rows in Numpy?

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 np.roll function requires three parameters: the array to be rolled (array_name), the shift amount (number_of_positions), and the axis (axis) specifying the dimension for the roll.

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]]

It is crucial to use the code np.roll(my_array, -1, axis=0) precisely as shown. Omitting axis=0 would result in a different outcome, shifting the elements within the rows rather than moving the rows themselves.

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.

See also  How to check if array is empty?