Given a 2D rectangular numpy array:
JavaScript
x
6
1
a = np.array([
2
[1, 2, 3],
3
[4, 5, 6],
4
[7, 8, 9]
5
])
6
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.
JavaScript
1
5
1
import numpy as np
2
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
3
result = np.triu(np.rot90(a)).sum() - np.trace(a)
4
#Output: 23
5