我一直在寻找一种方法(更有效,只是编写循环遍历矩阵)从包装对角线顺序给出的元素创建矩阵,并按此顺序提取值.举个例子,a = [2,3,4,5,6,7]我希望能够生成数组
[ 0, 2, 5, 7,
0, 0, 3, 6,
0, 0, 0, 4,
0, 0, 0, 0]
Run Code Online (Sandbox Code Playgroud)
并且还能够a从该阵列中重新提取.
scipy.sparse.diags实现了很多这样的东西,但顾名思义是为稀疏数组.numpy中是否有任何类型的功能可以提供此功能,或者某种形式的基于对角线的索引?或者也许某种类型的数组转换会使这更可行?
保持Josh Adel建议的方法,如果你想保持你的数据按对角线排序,而不是行,你只需要稍微回过头np.triu_indices来建立你自己的索引生成例程:
def my_triu_indices(n, k=0):
rows, cols = np.triu_indices(n, k)
rows = cols - rows - k
return rows, cols
Run Code Online (Sandbox Code Playgroud)
现在你可以这样做:
>>> a = np.array([2,3,4,5,6,7])
>>> b = np.zeros((4, 4), dtype=a.dtype)
>>> b[my_triu_indices(4, 1)] = a
>>> b
array([[0, 2, 5, 7],
[0, 0, 3, 6],
[0, 0, 0, 4],
[0, 0, 0, 0]])
>>> b[my_triu_indices(4, 1)]
array([2, 3, 4, 5, 6, 7])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
177 次 |
| 最近记录: |