这是一种方法:
def subdiag_prod_(a):
sub_diag = np.diagonal(a, offset=-1)
mask = np.triu(np.ones((sub_diag.shape*2))).astype('bool')
m = sub_diag[:,None].T * mask
ma = np.ma.array(sub_diag[:,None].T * mask, mask=~mask)
diag = np.prod(ma, axis=1).data
out = np.diag(diag)
last_row = np.zeros([out.shape[0]+1]*2)
last_row[:out.shape[0], :out.shape[1]] += out
return last_row
a = np.random.randint(1,5,(10,10))
array([[2, 2, 1, 4, 3, 1, 3, 1, 4, 4],
[2, 2, 2, 1, 1, 2, 3, 2, 2, 2],
[4, 2, 2, 4, 2, 1, 3, 3, 3, 4],
[2, 3, 3, 1, 1, 1, 4, 2, 3, 4],
[3, 3, 1, 1, 2, 1, 3, 4, 4, 3],
[1, 4, 4, 1, 1, 4, 1, 1, 1, 4],
[4, 2, 3, 2, 1, 4, 4, 1, 3, 2],
[4, 2, 2, 4, 4, 4, 1, 4, 3, 1],
[1, 3, 1, 1, 2, 2, 2, 3, 4, 1],
[1, 3, 2, 2, 3, 4, 1, 3, 2, 1]])
subdiag_prod(a)
array([[288., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 144., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 72., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 24., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 24., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 24., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 6., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 6., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 2., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]])
详情
第一步是用np.diagonal取ndarray的对角线:
sub_diag = np.diagonal(a, offset=-1)
# array([2, 2, 3, 1, 1, 4, 1, 3, 2])
我们可以通过使用np.tril 创建一个mask,然后我们可以使用它以指定的方式获取对角元素的乘积:
mask = np.triu(np.ones((sub_diag.shape*2))).astype('bool')
现在我们可以使用上面的ndarray 作为掩码,通过掩码和下对角线相乘来创建一个掩码数组:
mask = np.ma.array(sub_diag[:,None].T * mask, mask=~mask)
现在我们可以获取掩码数组的逐行乘积:
d = np.prod(ma, axis=1).data
# array([288, 144, 72, 24, 24, 24, 6, 6, 2])
然后简单地从中构建一个对角矩阵:
out = np.diag(d)
last_row = np.zeros([out.shape[0]+1]*2)
last_row[:out.shape[0], :out.shape[1]] += out