NumPy k-th diagonal indices

后端 未结 5 768
青春惊慌失措
青春惊慌失措 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:07

    A bit late, but this version also works for k = 0 (and does not alter the arrays, so does not need to make a copy).

    def kth_diag_indices(a, k):
        rows, cols = np.diag_indices_from(a)
        if k < 0:
            return rows[-k:], cols[:k]
        elif k > 0:
            return rows[:-k], cols[k:]
        else:
            return rows, cols
    

提交回复
热议问题