NumPy k-th diagonal indices

后端 未结 5 757
青春惊慌失措
青春惊慌失措 2020-12-28 17:00

I\'d like to do arithmetics with k-th diagonal of a numpy.array. I need those indices. For example, something like:

>>> a = numpy.eye(2)
>>>         


        
5条回答
  •  不知归路
    2020-12-28 17:24

    The indices of the k'th diagonal of a can be computed with

    def kth_diag_indices(a, k):
        rowidx, colidx = np.diag_indices_from(a)
        colidx = colidx.copy()  # rowidx and colidx share the same buffer
    
        if k > 0:
            colidx += k
        else:
            rowidx -= k
        k = np.abs(k)
    
        return rowidx[:-k], colidx[:-k]
    

    Demo:

    >>> a
    array([[ 0,  1,  2,  3,  4],
           [ 5,  6,  7,  8,  9],
           [10, 11, 12, 13, 14],
           [15, 16, 17, 18, 19],
           [20, 21, 22, 23, 24]])
    >>> a[kth_diag_indices(a, 1)]
    array([ 1,  7, 13, 19])
    >>> a[kth_diag_indices(a, 2)]
    array([ 2,  8, 14])
    >>> a[kth_diag_indices(a, -1)]
    array([ 5, 11, 17, 23])
    

提交回复
热议问题