如何计算二维数组中的次对角线平均值?

How to calculate secondary diagonals mean in a 2D array?

我想计算 NumPy 数组中每条次对角线的平均值。例如,我有这个数组:

    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]])

并且我想编写输出为的代码:

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

像这样的东西应该可以工作:

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

反转 b 所以 rb 的对角线是 b 的 anti-diagonals:

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

计算 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.        ])