【问题标题】:Converting 1D numpy array into top triangle of matrix将一维 numpy 数组转换为矩阵的顶部三角形
【发布时间】:2016-01-21 00:47:55
【问题描述】:

是否可以采用包含 171 个值的一维 numpy 数组并将这些值放入 18X18 矩阵的顶部三角形中?

我觉得我应该能够以某种方式使用 np.triu_indices 来执行此操作,但我无法完全弄清楚!

谢谢!

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    What is the most efficient way to get this kind of matrix from a 1D numpy array?Copy flat list of upper triangle entries to full matrix?

    大致的方法是

    result = np.zeros(...)
    ind = np.triu_indices(...)
    result[ind] = values
    

    细节取决于目标数组的大小,以及目标值的布局。

    In [680]: ind = np.triu_indices(4)
    In [681]: values = np.arange(16).reshape(4,4)[ind]
    In [682]: result = np.zeros((4,4),int)
    In [683]: result[ind]=values
    In [684]: values
    Out[684]: array([ 0,  1,  2,  3,  5,  6,  7, 10, 11, 15])
    In [685]: result
    Out[685]: 
    array([[ 0,  1,  2,  3],
           [ 0,  5,  6,  7],
           [ 0,  0, 10, 11],
           [ 0,  0,  0, 15]])
    

    【讨论】:

      猜你喜欢
      • 2022-10-25
      • 1970-01-01
      • 2018-12-28
      • 1970-01-01
      • 2016-07-15
      • 2022-11-29
      • 2021-10-12
      • 2016-02-02
      • 2011-04-18
      相关资源
      最近更新 更多