简体   繁体   English

替换 numpy 数组中的所有非对角线元素

[英]Replace all off diagonal elements in numpy array

I have below numpy array我有以下numpy数组

import numpy as np
np.identity(13)

Now I like to replace all off-diagonal elements with some other number, say 0.45.现在我想用其他数字替换所有非对角线元素,比如 0.45。

Is there any direct method available to perform this?有没有直接的方法可以执行此操作?

What about the following?那么以下呢?

import numpy as np
n = 13
val_offdiag = 0.45
val_diag = 1
a = np.full((n ,n), val_offdiag) - np.identity(n) * (val_offdiag - val_diag)

You can use numpy.where您可以使用numpy.where

np.where(np.identity(13)==0, 0.45, 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM