Direct way to generate sum of all parallel diagonals in Numpy / Pandas?

后端 未结 3 1407
深忆病人
深忆病人 2021-02-14 12:34

I have a rectangular (can\'t be assumed to be square) Pandas DataFrame of numbers. Say I pick a diagonal direction (either \"upperleft to lowerright\" or \"upperright to lowerl

3条回答
  •  臣服心动
    2021-02-14 13:24

    For a 2D numpy array A this might be (?) the shortest code to sum diagonals:

    np.bincount(sum(np.indices(A.shape)).flat, A.flat)
    

    To sum the opposite diagonals, you can np.fliplr the array.

提交回复
热议问题