是否可以采用包含171个值的1D numpy数组并将这些值放入18X18矩阵的顶部三角形中?
我觉得我应该能够以某种方式使用np.triu_indices来做到这一点,但我无法理解它!
谢谢!
答案 0 :(得分:4)
请参阅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]])