相关疑难解决方法(0)

将对称矩阵(2D阵列)的上/下三角形部分转换为1D阵列并将其返回到2D格式

这个问题阐述了如何访问lowerupper给定矩阵的triagular部分,说:

m = np.matrix([[11, 12, 13],
               [21, 22, 23],
               [31, 32, 33]])
Run Code Online (Sandbox Code Playgroud)

在这里,我需要在一维数组中转换矩阵,可以这样做:

indices = np.triu_indices_from(m)
a = np.asarray( m[indices] )[-1]
#array([11, 12, 13, 22, 23, 33])
Run Code Online (Sandbox Code Playgroud)

在进行大量计算后a,更改其值,它将用于填充对称的2D数组:

new = np.zeros(m.shape)
for i,j in enumerate(zip(*indices)):
    new[j]=a[i]
    new[j[1],j[0]]=a[i]
Run Code Online (Sandbox Code Playgroud)

返回:

array([[ 11.,  12.,  13.],
       [ 12.,  22.,  23.],
       [ 13.,  23.,  33.]])
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来实现这一目标?更具体地说,避免Python循环重建2D数组?

python arrays numpy matrix

5
推荐指数
3
解决办法
4390
查看次数

标签 统计

arrays ×1

matrix ×1

numpy ×1

python ×1