【问题标题】:Python matrix row shifting(Also column)Python矩阵行移位(也是列)
【发布时间】: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 matrix shift


【解决方案1】:

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]])
>>>

【讨论】:

    【解决方案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]))
    

    【讨论】:

    • 对我帮助很大!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多