Swap two Rows in a NumPy Array in Python

Swapping rows in NumPy array is used for data manipulations and mathematical computations .

Swapping Rows using numpy.roll()

roll() is method in python numpy module. roll() methods rolls an array elements along the axis that is specified.

Syntax :

numpy.roll(array,shift,axis=None)

Basic example to illustrate swapping rows using roll() method

#importing NumPy Module
import numpy as np

#Creating an array using NumPy
arr = np.array([[1,2],[6,7]])

print("Original array:")
print(arr) #printing or displaying the original array

arr = np.roll(arr,1,axis=0) #swapping rows using roll method of numpy

print("Array after swapping two rows:")
print(arr) #printing or displaying the array after swapping two rows

output:

Original array:
[[1 2]
[6 7]]
Array after swapping two rows:
[[6 7]
[1 2]]

Here, after inserting the array using numpy named “arr” .Using roll method , 1st parameter is the name of the array i.e “arr” , next parameter is “1”, this rotates the rows once and next is axis along which the matrix row must rotate .

 

 

Swapping Two Rows using NumPy Array using Assignment

This is by swapping two rows using traditional swapping mechanism .

#importing NumPy Module
import numpy as np

#Creating an array using NumPy
arr = np.array([[1,2],[6,7]])

print("Original array:")
print(arr) #printing or displaying the original array

#swapping rows using traditional swapping mechanism
temp = arr[0].copy()
arr[0] =arr[1]
arr[1] = temp

print("Array after swapping two rows:")
print(arr) #printing or displaying the array after swapping two rows

output :

Original array:
[[1 2]
[6 7]]
Array after swapping two rows:
[[6 7]
[1 2]]

Here ,  in “temp” variable 1st row values are stored . Then 2nd two values are stored in arr[0]  , then temp values are stored in arr[1]. By this way the rows are swapped using the formal assignment mechanism.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top