Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NumPy k-th diagonal indices

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)
>>> a[numpy.diag_indices(a, k=-1)] = 5
>>> a
array([[ 1.,  0.],
       [ 5.,  1.]])

Unfortunately, diag_indices only returns the indices comprising the main diagonal, so at the moment I am doing:

a += numpy.diag([5], -1)

But that doesn't seem as nice or robust. :-)

Is there a way in numpy to get indices for other than the main diagonal?

like image 368
K3---rnc Avatar asked Jun 07 '12 04:06

K3---rnc


People also ask

How do you select a diagonal element in Python?

diagonal() With the help of Numpy matrix. diagonal() method, we are able to find a diagonal element from a given matrix and gives output as one dimensional matrix.


1 Answers

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
like image 115
Hans Then Avatar answered Sep 20 '22 18:09

Hans Then