1

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.

Rutger Hofste
  • 4,073
  • 3
  • 33
  • 44
  • 1
    What are you considering diagonal? I do not know why 9 is included. – msi_gerva Jun 04 '19 at 15:08
  • "Diagonal" as in 'towards the right and downwards of the secondary diagonal', perhaps? – TrebledJ Jun 04 '19 at 15:10
  • good point. Its the lower left to upper right diagonal. Edited the question. – Rutger Hofste Jun 04 '19 at 16:11
  • Please [accept](http://meta.stackexchange.com/questions/5234) an answer if you think it solves your problem. It will help community at large to recognize the correct solution. This can be done by clicking the green check mark next to the answer. See this [image](http://i.stack.imgur.com/uqJeW.png) for reference. Cheers. – Austin Jun 08 '19 at 06:05

3 Answers3

2

You can use 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
Austin
  • 25,759
  • 4
  • 25
  • 48
1

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
Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33
0

You can use scipy.spatial.distance.squareform to select your triangle of interest:

from scipy.spatial.distance import squareform
squareform(a[::-1], checks=False)
# array([8, 9, 6])
squareform(a[::-1], checks=False).sum()
# 23 
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99