How to Swap Two Rows in a NumPy Array
Last Updated :
24 Apr, 2025
One common task you might encounter when working with NumPy arrays is the need to swap two rows. Swapping rows can be essential in data preprocessing, reshaping data, or reordering data to perform specific analyses in Python. In this article, we will explore different methods to swap two rows in a NumPy array. In this article, we will see how to swap two rows in a NumPy Array.
Swapping Two Rows in NumPy array
Below are some methods and ways by which we can swap two rows in a NumPy Array:
Swapping Rows using np.roll()
In this example, we are using numpy.roll() to swap two rows in a NumPy Array. As we can see in the given example, the 0th row is swapped with the 2nd row, the 1st with the 3rd row, and so on.
Python3
# Swapping two rows in a given numPy array
# Importing NumPy Module
import numpy as np
# Creating a NumPy array
num_arr = np.array([[1,3,1], [3,1,3], [2,9,2], [9,2,9]])
# Displaying the original array
print("Original array:")
print(num_arr)
# Using np.roll() method for swapping array along row
num_arr = np.roll(num_arr,2,axis=0)
print("\nArray after swapping the rows:")
print(num_arr)
Output
Original array:
[[1 3 1]
[3 1 3]
[2 9 2]
[9 2 9]]Array after swapping the rows:
[[2 9 2]
[9 2 9]
[1 3 1]
[3 1 3]]
Swapping Rows of a NumPy Array using Advanced Indexing
In this example, we are using advanced indexing to swap two rows in a NumPy Array. Here, 0th and 3rd rows of NumPy array are swapped using advance indexing.
Python3
# Swapping two rows in a given numPy array
# Importing NumPy Module
import numpy as np
# Creating a NumPy array
num_arr = np.array([[1,3,1], [3,1,3], [2,9,2], [9,2,9]])
# Displaying the original array
print("Original array:")
print(num_arr)
# Swapping 0th and 3rd rows
num_arr[[0,3]] = num_arr[[3,0]]
print("\nArray after swapping the rows:")
print(num_arr)
Output:
Original array:
[[1 3 1]
[3 1 3]
[2 9 2]
[9 2 9]]
Array after swapping the rows:
[[9 2 9]
[3 1 3]
[2 9 2]
[1 3 1]]
Python Swapping Rows using NumPy Indexing
In this example, we are using NumPy indexing to swap two rows in a NumPy Array. Here, 0th, 1st and 3nd rows of NumPy array are swapped using numpy indexing.
Python3
# Swapping two rows in a given numPy array
# Importing NumPy Module
import numpy as np
# Creating a NumPy array
num_arr = np.array([[3, 2, 1], [6, 5, 4], [9, 8, 7]])
# Displaying the original array
print("Original array:")
print(num_arr)
# Swapping 0th and 1st and 2nd rows
num_arr = num_arr[[2 , 0, 1]]
print("\nArray after swapping the rows:")
print(num_arr)
Output:
Original array:
[[3 2 1]
[6 5 4]
[9 8 7]]
Array after swapping the rows:
[[9 8 7]
[3 2 1]
[6 5 4]]
Swapping the Rows in NumPy Array using Direct Assignment
In the given example, 1st and 2nd rows of NumPy array are swapped using direct assignment.
Python3
# Swapping two rows in a given numPy array
# Importing NumPy Module
import numpy as np
# Creating a NumPy array
num_arr = np.array([[3, 2, 1], [6, 6, 6], [8, 8, 8]])
# Displaying the original array
print("Original array:")
print(num_arr)
# Swapping 1st and 2nd rows
temp = num_arr[1].copy()
num_arr[1] = num_arr[2]
num_arr[2] = temp
print("\nArray after swapping the rows:")
print(num_arr)
Output
Original array:
[[3 2 1]
[6 6 6]
[8 8 8]]
Array after swapping the rows:
[[3 2 1]
[8 8 8]
[6 6 6]]
Swapping the Rows in Python NumPy Array using User Input
In the given example, we are taking user input and then swapping the rows.
Python3
# Swapping two rows in a given numPy array
# Importing NumPy Module
import numpy as np
# Creating a NumPy array
num_arr = np.array([[1, 1, 1], [6, 6, 6], [8, 8, 8], [0, 0, 0]])
# Displaying the original array
print("Original array:")
print(num_arr)
# Defining Swap function
def Swap(arr, firstIndex, secondIndex):
arr[[firstIndex, secondIndex]] = arr[[secondIndex, firstIndex]]
# Passing parameter to Swap function
Swap(num_arr, 0, 3)
print("\nArray after swapping the rows:")
print(num_arr)
Output
Original array:
[[1 1 1]
[6 6 6]
[8 8 8]
[0 0 0]]
Array after swapping the rows:
[[0 0 0]
[6 6 6]
[8 8 8]
[1 1 1]]
Similar Reads
How to append two NumPy Arrays?
Prerequisites: Numpy Two arrays in python can be appended in multiple ways and all possible ones are discussed below. Method 1: Using append() method This method is used to Append values to the end of an array. Syntax : numpy.append(array, values, axis = None) Parameters : array: [array_like]Input a
4 min read
How to swap columns of a given NumPy array?
In this article, let's discuss how to swap columns of a given NumPy array. Approach : Import NumPy moduleCreate a NumPy arraySwap the column with IndexPrint the Final array Example 1: Swapping the column of an array. Python3 # importing Module import numpy as np # creating array with shape(4,3) my_
2 min read
NumPy Array Sorting | How to sort NumPy Array
Sorting an array is a very important step in data analysis as it helps in ordering data, and makes it easier to search and clean. In this tutorial, we will learn how to sort an array in NumPy. You can sort an array in NumPy: Using np.sort() functionin-line sortsorting along different axesUsing np.ar
4 min read
How to Set Axis for Rows and Columns in NumPy ?
In this article, we are going to see how to set the axis for rows and columns in NumPy. Functions Usednp.array(object): to create a NumPy array, the object is the parameter that contains the arraynp.reshape(rows, columns): to reshape the array into the specified number of rows and columns. Here in t
3 min read
How to normalize an array in NumPy in Python?
In this article, we are going to discuss how to normalize 1D and 2D arrays in Python using NumPy. Normalization refers to scaling values of an array to the desired range. Normalization of 1D-Array Suppose, we have an array = [1,2,3] and to normalize it in range [0,1] means that it will convert arra
3 min read
How to randomly select rows of an array in Python with NumPy ?
In this article, we will see two different methods on how to randomly select rows of an array in Python with NumPy. Let's see different methods by which we can select random rows of an array: Method 1: We will be using the function shuffle(). The shuffle() function shuffles the rows of an array rand
2 min read
How to skip every Nth index of NumPy array ?
NumPy arrays offer efficient numerical operations and data storage. When working with large arrays, sometimes it's necessary to skip specific indices for optimization or data processing purposes. This article will show how to skip every Nth index of the NumPy array. There are various ways to access
4 min read
Find unique rows in a NumPy array
In this article, we will discuss how to find unique rows in a NumPy array. To find unique rows in a NumPy array we are using numpy.unique() function of NumPy library. Syntax of np.unique() in Python Syntax: numpy.unique() Parameter: ar: arrayreturn_index: Bool, if True return the indices of the inpu
3 min read
How to Change a Single Value in a NumPy Array
NumPy arrays are a fundamental data structure in Python, widely used for scientific computing and data analysis. They offer a powerful way to perform operations on large datasets efficiently. One common task when working with NumPy arrays is changing a single value within the array. This article wil
6 min read
How to Convert NumPy Matrix to Array
In NumPy, a matrix is essentially a two-dimensional NumPy array with a special subclass. In this article, we will see how we can convert NumPy Matrix to Array. Also, we will see different ways to convert NumPy Matrix to Array. Convert Python NumPy Matrix to an ArrayBelow are the ways by which we can
3 min read