【发布时间】:2021-10-26 16:12:29
【问题描述】:
有什么方法可以在 python 中移动特定的行? (如果使用 numpy 会很好)。 我想要
[[1,2],
[3,4]]
成为
[[1,2],
[4,3]].
也为专栏好!
[[1,2],
[3,4]]
成为
[[1,4],
[3,2]]
.
谢谢。
【问题讨论】:
-
你的矩阵总是 2x2 吗?
有什么方法可以在 python 中移动特定的行? (如果使用 numpy 会很好)。 我想要
[[1,2],
[3,4]]
成为
[[1,2],
[4,3]].
也为专栏好!
[[1,2],
[3,4]]
成为
[[1,4],
[3,2]]
.
谢谢。
【问题讨论】:
np.roll 是你的朋友。
>>> import numpy as np
>>> x = np.array([[1,2],[3,4]])
>>> x
array([[1, 2],
[3, 4]])
>>> x[1]
array([3, 4])
>>> np.roll(x[1],1)
array([4, 3])
>>> x[1] = np.roll(x[1],1)
>>> x
array([[1, 2],
[4, 3]])
>>> x[1] = np.roll(x[1],1)
>>> x[:,1]
array([2, 4])
>>> x[:,1] = np.roll(x[:,1],1)
>>> x
array([[1, 4],
[3, 2]])
>>>
【讨论】:
对于换行,你可以这样做:
import numpy as np
matrix = np.random.rand(5, 5)
row_no = 2
matrix[row_no, :] = np.array([matrix[row_no, -1]] + list(matrix[row_no, :-1]))
同样对于列移动,您可以简单地切换维度顺序。
import numpy as np
matrix = np.random.rand(5, 5)
col_no = 2
matrix[:, col_no] = np.array([matrix[-1, col_no]] + list(matrix[:-1, col_no]))
【讨论】: