如何获得 numpy 中对角线下的值总和?

How do I get the sum of values under a diagonal in numpy?

给定一个二维矩形 numpy 数组:

a = np.array([
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
])

我想对左下角到右上角的对角线下的所有值求和,即896

完成此任务的最佳方法是什么?

该方法也适用于大型数组。

您可以使用 np.flip + np.tril + np.sum:

import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print(np.sum(np.tril(np.flip(a, 1), -1)))
# 23

可以旋转,对上三角求和,减去对角线。

import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
result = np.triu(np.rot90(a)).sum() - np.trace(a)
#Output: 23

您可以使用 scipy.spatial.distance.squareform 到 select 您感兴趣的三角形:

from scipy.spatial.distance import squareform
squareform(a[::-1], checks=False)
# array([8, 9, 6])
squareform(a[::-1], checks=False).sum()
# 23