Applied Statistics - 应用统计学习 - numpy array交换两行 ? How to Swap Two Rows in a NumPy Array (With Example)

发布时间 2023-12-30 11:15:30作者: abaelhe

https://www.statology.org/qualitative-vs-quantitative-variables/

https://www.statology.org/numpy-swap-rows/
How to Swap Two Rows in a NumPy Array (With Example)
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: