20.5 C
London
Monday, June 2, 2025
HomePandas in PythonGeneral Functions in PythonHow to Swap Two Rows in a NumPy Array (With Example)

How to Swap Two Rows in a NumPy Array (With Example)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following basic syntax to swap two rows in a NumPy array:

some_array[[0, 3]] = some_array[[3, 0]]

This particular example will swap the first and fourth rows in the NumPy array called some_array.

All other rows will remain in their original positions.

The following example shows how to use this syntax in practice.

Example: Swap Two Rows in NumPy Array

Suppose we have the following NumPy array:

import numpy as np

#create NumPy array
some_array = np.array([[1, 1, 2], [3, 3, 7], [4, 3, 1], [9, 9, 5], [6, 7, 7]])

#view NumPy array
print(some_array)

[[1 1 2]
 [3 3 7]
 [4 3 1]
 [9 9 5]
 [6 7 7]]

We can use the following syntax to swap the first and fourth rows in the NumPy array:

#swap rows 1 and 4
some_array[[0, 3]] = some_array[[3, 0]]

#view updated NumPy array
print(some_array)

[[9 9 5]
 [3 3 7]
 [4 3 1]
 [1 1 2]
 [6 7 7]]

Notice that the first and fourth rows have been swapped.

All other rows remained in their original positions.

Note that some_array[[0,  3]] is shorthand for some_array[[0, 3],  :] so we could also use the following syntax to get the same results:

#swap rows 1 and 4
some_array[[0, 3], :] = some_array[[3, 0], :]

#view updated NumPy array
print(some_array)

[[9 9 5]
 [3 3 7]
 [4 3 1]
 [1 1 2]
 [6 7 7]]

Notice that the first and fourth rows have been swapped.

This result matches the result from using the shorthand notation in the previous example.

Feel free to use whichever notation you prefer to swap two rows in a given NumPy array.

Additional Resources

The following tutorials explain how to perform other common tasks in NumPy:

How to Remove Duplicate Elements in NumPy Array
How to Replace Elements in NumPy Array
How to Rank Items in NumPy Array

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories