【问题标题】:Is there a function in numpy to replace lower and upper diagonal values of a numpy array?numpy 中是否有一个函数来替换 numpy 数组的上下对角线值?
【发布时间】:2012-05-26 16:31:55
【问题描述】:

要替换我使用的主对角线np.fill_diagonal

matrix = np.zeros((4, 4), float)
main = np.array([2,2,2,2])
np.fill_diagonal(matrix, main)

但我还需要替换主对角线旁边的上下对角线:

upper=np.array([1,1,1])
lower=np.array([7,7,7])

得到:

matrix=[[2 1 0 0]
        [7 2 1 0]
        [0 7 2 1]
        [0 0 7 2]]

谢谢

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    通过一些智能切片,np.fill_diagonal 也可以做到这一点:

    >>> np.fill_diagonal(matrix[:-1, 1:], upper)
    >>> np.fill_diagonal(matrix[1:, :-1], lower)
    >>> matrix
    array([[ 2.,  1.,  0.,  0.],
           [ 7.,  2.,  1.,  0.],
           [ 0.,  7.,  2.,  1.],
           [ 0.,  0.,  7.,  2.]])
    

    【讨论】:

      猜你喜欢
      • 2021-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      • 2015-09-01
      相关资源
      最近更新 更多