【问题标题】:Diagonal array in numpynumpy中的对角线数组
【发布时间】:2022-01-26 00:23:19
【问题描述】:

如果我有数组[[1,0,0],[0,1,0],[0,0,1]](我们称之为So),它是作为numpy.eye(3) 完成的。 我怎样才能得到对角线以下的元素只有 2 和 3 像这样[[1,0,0],[2,1,0],[3,2,1]] ?如何将数组的向量分配给不同的值集?

我知道我可以使用numpy.concatenate 连接 3 个向量,并且我知道如何更改行/列,但我不知道如何更改主对角线下方的对角线。

我尝试通过 np.diagonal(So,-1)=2*np.diagonal(So,-1) 更改主对角线正下方的对角线,但收到错误消息 cannot assign to function call

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    我不会从numpy.eye 开始,而是从numpy.ones 开始并使用numpy.tril+cumsum 来计算下三角形上的下一个数字:

    import numpy as np
    np.tril(np.ones((3,3))).cumsum(axis=0).astype(int)
    

    输出:

    array([[1, 0, 0],
           [2, 1, 0],
           [3, 2, 1]])
    
    反转输出(来自评论)

    假设数组是正方形的

    n = 3
    a = np.tril(np.ones((n,n)))
    (a*(n+2)-np.eye(n)*n-a.cumsum(axis=0)).astype(int)
    

    输出:

    array([[1, 0, 0],
           [3, 1, 0],
           [2, 3, 1]])
    

    n=5 的输出:

    array([[1, 0, 0, 0, 0],
           [5, 1, 0, 0, 0],
           [4, 5, 1, 0, 0],
           [3, 4, 5, 1, 0],
           [2, 3, 4, 5, 1]])
    

    【讨论】:

    • 太好了!我不知道 cumsum 函数如果想要的输出是 [[1,0,0],[3,1,0],[2,3,1]],你知道怎么做吗?谢谢你:)
    • @Gon 这取决于,4x4 数组的输出是什么?还有 5x4?
    • 不确定这是否是您想要的,但我提供了更新
    • 感谢您的回答@mozway! :)
    【解决方案2】:

    您可以使用np.fill_diagonal 并索引矩阵,这样矩阵的主对角线就是您想要的。假设您想输入 2 和 3 以外的其他值是一个很好的解决方案:

    import numpy as np
    
    q = np.eye(3)
    
    
    #if you want the first diagonal below the principal
    # you can call q[1:,:] (this is not a 3x3 or 2x3 matrix but it'll work)
    
    val =2
    np.fill_diagonal(q[1:,:], val)
    #note that here you can use an unique value 'val' or 
    # an array with values of corresponding size
    #np.fill_diagonal(q[1:,:], [2, 2])
    
    #then you can do the same on the last one column
    
    np.fill_diagonal(q[2:,:], 3)
    

    【讨论】:

    • 这很聪明!谢谢!
    【解决方案3】:

    您可以采用这种方法:

    def func(n):
    ...     return np.array([np.array(list(range(i, 0, -1)) + [0,] * (n - i)) for i in range(1, n + 1)])
    
    func(3)
    

    输出

    array([[1, 0, 0],
           [2, 1, 0],
           [3, 2, 1]])
    

    【讨论】:

      猜你喜欢
      • 2015-05-09
      • 1970-01-01
      • 1970-01-01
      • 2011-05-25
      • 2021-05-11
      • 2021-05-15
      • 1970-01-01
      • 2012-06-05
      • 2023-04-07
      相关资源
      最近更新 更多