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

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], :]
OR
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:

posted @   abaelhe  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示