Home > Software design >  How to calculate secondary diagonals mean in a 2D array?
How to calculate secondary diagonals mean in a 2D array?

Time:05-23

I want to calculate the mean of each secondary diagonal in the NumPy array. For example, I have this array :

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

and I want to write a code that the output would be:

    np.array([1, 4.5, 4.6, 5, 6, 8, 3.6, 4, 9])

CodePudding user response:

Something like this should work:

In [47]: b
Out[47]: 
array([[ 1,  3,  4,  2],
       [ 6,  3,  5,  1],
       [ 7,  8,  9, 12],
       [ 5,  6,  9,  3],
       [ 8,  7,  3,  2],
       [ 4,  5,  6,  9]])

In [48]: nr, nc = b.shape

Reverse b so the diagonals of rb are the anti-diagonals of b:

In [49]: rb = b[::-1]

Compute the means of the diagonals of rb:

In [50]: np.array([np.diagonal(rb, k).mean() for k in range(1 - nr, nc)])
Out[50]:
array([1.        , 4.5       , 4.66666667, 5.        , 6.        ,
       8.        , 3.66666667, 4.        , 9.        ])

  • Related