Is there any way that I can shift specific row in python? (It would be nice if numpy is used). I want
[[1,2],
[3,4]]
to be
[[1,2],
[4,3]].
Also for the column would be nice!
[[1,2],
[3,4]]
to be
[[1,4],
[3,2]]
.
Thank you.
CodePudding user response:
np.roll
is your friend.
>>> 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]])
>>>
CodePudding user response:
For the row shifting you can do:
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]))
and similarly for column shifting you can simply switch the dimension orders.
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]))