Python 获取高数组的对角索引
我有一个大小为5 x 3 x 3的数组。Python 获取高数组的对角索引,python,numpy,multidimensional-array,numpy-ndarray,diagonal,Python,Numpy,Multidimensional Array,Numpy Ndarray,Diagonal,我有一个大小为5 x 3 x 3的数组。 我想用数字填充每个3 x 3块的对角线。 如何使用numpy(一个python库)高效地实现这一点 我的出发点是: [[[0 0 0] [0 0 0] [0 0 0]] [[0 0 0] [0 0 0] [0 0 0]] [[0 0 0] [0 0 0] [0 0 0]] [[0 0 0] [0 0 0] [0 0 0]] [[0 0 0] [0 0 0] [0 0 0]]] 我想要这样的东西:
我想用数字填充每个3 x 3块的对角线。
如何使用numpy(一个python库)高效地实现这一点 我的出发点是:
[[[0 0 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]]
我想要这样的东西:
[[[0.07735655 0 0 ]
[0 0.11476396 0 ]
[0 0 0.09903619]]
[[0.1923885 0 0 ]
[0 0.03063454 0 ]
[0 0 0.06028193]]
[[0.06566275 0 0 ]
[0 0.03151423 0 ]
[0 0 0.04042383]]
[[0.07950743 0 0 ]
[0 0.03250461 0 ]
[0 0 0.0448308 ]]
[[0.10879917 0 0 ]
[0 0.04700161 0 ]
[0 0 0.03924387]]]
您可以使用以下选项:
diag_ind_y, diag_ind_x = np.diag_indices(3)
arr1[:, diag_ind_y, diag_ind_x] = diag_vals
测试它:
import numpy as np
arr1 = np.zeros(shape=(5,3,3), dtype=np.float64) # Your array
diag_vals = np.random.rand(5,3) # The source of your diag values
diag_ind_y, diag_ind_x = np.diag_indices(3) # Returns arrays [0,1,2] and [0,1,2]
arr1[:, diag_ind_y, diag_ind_x] = diag_vals
print (arr1)
[[[0.69514006 0. 0. ]
[0. 0.4014048 0. ]
[0. 0. 0.473671 ]]
[[0.12769874 0. 0. ]
[0. 0.8565723 0. ]
[0. 0. 0.69453857]]
[[0.00943213 0. 0. ]
[0. 0.81497541 0. ]
[0. 0. 0.6915095 ]]
[[0.33894452 0. 0. ]
[0. 0.24649647 0. ]
[0. 0. 0.61987433]]
[[0.30184036 0. 0. ]
[0. 0.66978532 0. ]
[0. 0. 0.34574364]]]
输出:
import numpy as np
arr1 = np.zeros(shape=(5,3,3), dtype=np.float64) # Your array
diag_vals = np.random.rand(5,3) # The source of your diag values
diag_ind_y, diag_ind_x = np.diag_indices(3) # Returns arrays [0,1,2] and [0,1,2]
arr1[:, diag_ind_y, diag_ind_x] = diag_vals
print (arr1)
[[[0.69514006 0. 0. ]
[0. 0.4014048 0. ]
[0. 0. 0.473671 ]]
[[0.12769874 0. 0. ]
[0. 0.8565723 0. ]
[0. 0. 0.69453857]]
[[0.00943213 0. 0. ]
[0. 0.81497541 0. ]
[0. 0. 0.6915095 ]]
[[0.33894452 0. 0. ]
[0. 0.24649647 0. ]
[0. 0. 0.61987433]]
[[0.30184036 0. 0. ]
[0. 0.66978532 0. ]
[0. 0. 0.34574364]]]
将
循环与一起使用如何
这些数字进入对角线的来源是什么?随机数?或者其他数组——如果是,是什么形状?它是一个大小等于第一维度(5)*最后维度(3)的数组。i、 e:5 x 3