python - 为每个 python numpy 用不同的值填充矩阵对角线

标签 python numpy

我看到一个函数 numpy.fill_diagonal 为对角线元素分配相同的值。但我想为每个对角线元素分配不同的随机值。我怎样才能在 python 中做到这一点?可能正在使用 scipy 或其他库?

最佳答案

docs将填充 val 称为标量 is an existing documentation bug .事实上,任何可以在这里广播的值都是可以的。

填充对角线可以很好地处理类数组:

>>> a = np.arange(1,10).reshape(3,3)
>>> a
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> np.fill_diagonal(a, [99, 42, 69])
>>> a
array([[99,  2,  3],
       [ 4, 42,  6],
       [ 7,  8, 69]])

这是一个跨步技巧,因为对角线元素按数组的宽度 + 1 规则间隔。

从文档字符串来看,这比使用 np.diag_indices 更好:

Notes
-----
.. versionadded:: 1.4.0

This functionality can be obtained via `diag_indices`, but internally
this version uses a much faster implementation that never constructs the
indices and uses simple slicing.

关于python - 为每个 python numpy 用不同的值填充矩阵对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40261325/

相关文章:

python - 为什么将多处理与实例方法与函数一起使用时会得到不同的结果?

python - 非均匀间距的 Numpy 或 SciPy 导数函数?

python - 如何在 python 中将 unicode 字符串(来自 JSON 的字符串)编码为 'utf-8'?

python - 如何从 Python 中的图像中获取信噪比?

python - 类似字典的对象,没有 __getitem__、__setitem__

python - 具有 NaN 值的 Scipy 中的 T 检验

python - 避免使用多个 if 语句

python - Scipy 稀疏 Cumsum

python - 如何在 Python 中根据日期进行分类/计数

python - 如何在keras中使用一维卷积神经网络解决音频信号问题