In numpy docs for diagonal
it is said
Starting in NumPy 1.9 it returns a read-only view on the original
array. Attempting to write to the resulting array will produce an
error.
In some future release, it will return a read/write view and writing
to the returned array will alter your original array. The returned
array will have the same type as the input array.
If you don’t write to the array returned by this function, then you
can just ignore all of the above.
If you depend on the current behavior, then we suggest copying the
returned array explicitly, i.e., use np.diagonal(a).copy() instead of
just np.diagonal(a). This will work with both past and future versions
of NumPy.
So you should use np.diagonal(a).copy()
to get modifiable array.
If you need to edit a diagonal of your matrix you can use this answer by Hans Then.
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
x[kth_diag_indices(x,1)] = 2 # to make them all equal to 2