英文:
How to populate an 2D array from a list left to right with the diagonal being all zeroes
问题
idmatrixlist=[0.61, 0.63, 0.54, 0.82, 0.58, 0.57]
我需要从左到右填充一个数组,同时保持对角线上的零,使得最终的数组看起来像是这样。
我尝试了以下代码,但结果是条目的顺序错误的。
lowertriangleidmatrix = np.zeros((4,4))
indexer = np.tril_indices(4,k=-1)
lowertriangleidmatrix[indexer] = idmatrixlist
print(lowertriangleidmatrix)
结果:
[[0. 0. 0. 0. ]
[0.61 0. 0. 0. ]
[0.63 0.54 0. 0. ]
[0.82 0.58 0.57 0. ]]
英文:
I have a list:
idmatrixlist=[0.61, 0.63, 0.54, 0.82, 0.58, 0.57]
I need to populate an array from left to right while maintaining the zeroes on the diagonal so that the resulting array looks like.
I have tried the following code but it results in the wrong ordering of the entries.
lowertriangleidmatrix = np.zeros((4,4))
indexer = np.tril_indices(4,k=-1)
lowertriangleidmatrix[indexer] = idmatrixlist
print(lowertriangleidmatrix)
result:
[[0. 0. 0. 0. ]
[0.61 0. 0. 0. ]
[0.63 0.54 0. 0. ]
[0.82 0.58 0.57 0. ]]
How can this be re-ordered?
答案1
得分: 3
你可以使用 [`triu_indices`](https://numpy.org/doc/stable/reference/generated/numpy.triu_indices.html) 并反转 x/y:
```python
lowertriangleidmatrix = np.zeros((4, 4))
indexer = np.triu_indices(4, k=1)[::-1]
# (array([0, 0, 1, 0, 1, 2]), array([1, 2, 2, 3, 3, 3]))
lowertriangleidmatrix[indexer] = idmatrixlist
print(lowertriangleidmatrix)
输出:
[[0. 0. 0. 0. ]
[0.61 0. 0. 0. ]
[0.63 0.82 0. 0. ]
[0.54 0.58 0.57 0. ]]
英文:
You can use triu_indices
and invert the x/y:
lowertriangleidmatrix = np.zeros((4, 4))
indexer = np.triu_indices(4, k=1)[::-1]
# (array([0, 0, 1, 0, 1, 2]), array([1, 2, 2, 3, 3, 3]))
lowertriangleidmatrix[indexer] = idmatrixlist
print(lowertriangleidmatrix)
Output:
[[0. 0. 0. 0. ]
[0.61 0. 0. 0. ]
[0.63 0.82 0. 0. ]
[0.54 0.58 0.57 0. ]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论