Numpy modify ndarray diagonal Numpy modify ndarray diagonal numpy numpy

Numpy modify ndarray diagonal


If X is your array and c is the factor,

X[np.diag_indices_from(X)] /= c

See diag_indices_from in the Numpy manual.


A quick way to access the diagonal of a square (n,n) numpy array is with arr.flat[::n+1]:

n = 1000c = 20a = np.random.rand(n,n)a[np.diag_indices_from(a)] /= c # 119 microsecondsa.flat[::n+1] /= c # 25.3 microseconds


The np.fill_diagonal function is quite fast:

np.fill_diagonal(a, a.diagonal() / c)

where a is your array and c is your factor. On my machine, this method was as fast as @kwgoodman's a.flat[::n+1] /= c method, and in my opinion a bit clearer (but not as slick).