获取 tall 数组的对角线索引

Get Diagonal indexes for a tall array

我有一个大小为 5 x 3 x 3 的数组。
我想用数字填充每个 3 x 3 块的对角线。
我如何使用 numpy(A 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]]]

使用 for 循环和 numpy.fill_diagonal 怎么样?

In [33]: zeros = np.zeros((5, 3, 3))

# desired values to be filled along the diagonals; 
# can also be 1D numpy arrays instead of Python lists
In [34]: diagonals = [[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

In [35]: for idx, diag in enumerate(diagonals):
    ...:     np.fill_diagonal(zeros[idx], diag)
    ...:     

In [36]: zeros
Out[36]: 
array([[[1., 0., 0.],
        [0., 2., 0.],
        [0., 0., 3.]],

       [[1., 0., 0.],
        [0., 2., 0.],
        [0., 0., 3.]],

       [[1., 0., 0.],
        [0., 2., 0.],
        [0., 0., 3.]],

       [[1., 0., 0.],
        [0., 2., 0.],
        [0., 0., 3.]],

       [[1., 0., 0.],
        [0., 2., 0.],
        [0., 0., 3.]]])