有什么辦法可以在python中移動特定行嗎?(如果使用 numpy 會很好)。我想要
[[1,2],
[3,4]]
成為
[[1,2],
[4,3]].
也為列會很好!
[[1,2],
[3,4]]
成為
[[1,4],
[3,2]]
.
謝謝你。
uj5u.com熱心網友回復:
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]])
>>>
uj5u.com熱心網友回復:
對于行移位,您可以執行以下操作:
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]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338373.html
