Skip to content
Advertisement

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

Given a 2D rectangular numpy array:

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

I would like to take the sum of all values under the lower left to upper right diagonal , I.E. 8, 9 and 6.

What is the best way to accomplish this?

The method should work for large arrays too.

Advertisement

Answer

You can rotate, sum the upper triangle, and subtract the diagonal.

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement