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

后端 未结 3 1399
深忆病人
深忆病人 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:18

    You may be looking for numpy.trace(), documented here, to get the trace directly, or numpy.diagonal() to get the diagonal vector, documented here

    First, convert your dataframe to a numpy matrix using rectdf.as_matrix()

    Then:

    np.trace(matrix, offset)
    

    The offset, which can be either positive or negative, does the shifting you require.

    For example, if we do:

    a = np.arange(15).reshape(5, 3)
    for x in range(-4, 3): print np.trace(a, x)
    

    We get output:

    12
    22
    30
    21
    12
    6
    2
    

    To do this for a general matrix, we want the range from -(rows - 1) to columns, i.e. if we have a variable rows and a variable columns:

    a = np.arange(rows * columns).reshape(rows, columns)
    for x in range(-(rows - 1), columns): print np.trace(a, x)
    

提交回复
热议问题