Learn how to swap rows in NumPy arrays using indexing or the np.roll() function for efficient array manipulation.

How to Swap Rows in NumPy Arrays Using Direct Indexing
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.
This method swaps rows 0 and 1 in-place without creating new arrays or affecting other rows or elements.
How to Rotate/Shift Rows Using NumPy’s np.roll() Function
While np.roll() rotates rows rather than swapping two specific rows, it can shift row positions cyclically along the array.
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.
The syntax np.roll(array, -1, axis=0) shifts rows up by 1 position (negative shift), moving the first row to the end cyclically.
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]]
The axis parameter is critical: axis=0 rotates rows (moves entire rows), axis=1 rotates within rows (moves individual elements horizontally), omitting it flattens the array.
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]]
Without axis=0, np.roll() flattens the array to 1D, then rotates all elements, destroying the row structure and redistributing values across rows.
