如何从左到右将一个二维数组从列表中填充,对角线上都是零。

huangapple go评论57阅读模式
英文:

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.  ]]

huangapple
  • 本文由 发表于 2023年2月19日 19:51:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75499934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定