用python替换2D数组的对角线 [英] Replace diagonals of a 2D array with python

查看:243
本文介绍了用python替换2D数组的对角线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下2D数组

A=([[1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16])

我想用数组替换主对角线

And I want to replace the main diagonal by the array

a = ([0,2,15,20])

因此,结果必须是

A=([[0, 2, 3, 4],
    [5, 2, 7, 8],
    [9, 10, 15, 12],
    [13, 14, 15, 20])

我尝试使用np.diag(a,k = 0),但是它不起作用,因为np.diag()创建了一个带有数组"a"的对角2D数组.

I tried with np.diag(a, k=0) but it doesn't work because np.diag() creates a diagonal 2D array with the array "a".

有没有办法用numpy做到这一点? 上面的例子是最简单的例子.我希望不仅可以更改邮件对角线,还可以更改所有对角线.

Is there a way to do that with numpy? The above example is the simplest one. I would like to be able to change not only the mail diagonal but all diagonals.

推荐答案

您可以使用

You can use np.fill_diagonal(..) for that. Like the documentation says:

numpy.fill_diagonal(a, val, wrap=False)

numpy.fill_diagonal(a, val, wrap=False)

填充任意维的给定数组的主对角线.

Fill the main diagonal of the given array of any dimensionality.

例如:

np.fill_diagonal(A, 20)

因此,我们在整个对角线上广播 20.

We here thus broadcast 20 over the entire diagonal.

您也可以用不同的值填充对角线,例如:

You can also fill the diagonal with different values, like:

np.fill_diagonal(A, [0,2,15,20])

例如:

>>> a = np.zeros((4,4))
>>> np.fill_diagonal(a, [0,2,15,20])
>>> a
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  2.,  0.,  0.],
       [ 0.,  0., 15.,  0.],
       [ 0.,  0.,  0., 20.]])

如果要更改其他对角线,则只需镜像阵列即可.例如,对于 antidiagonal ,我们可以使用:

In case you want to change other diagonals, then it is a matter of mirroring the array. For example for the antidiagonal, we can use:

np.fill_diagonal(A[::-1], -20)

然后我们得到:

>>> A = np.zeros((4,4))
>>> np.fill_diagonal(A[::-1], -20)
>>> A
array([[  0.,   0.,   0., -20.],
       [  0.,   0., -20.,   0.],
       [  0., -20.,   0.,   0.],
       [-20.,   0.,   0.,   0.]])

如果我们不考虑超对角线次对角线,则 n 维矩阵具有 n×(n-1 )对角线.我们可以通过镜像一个或多个尺寸来分配它.

If we do not take superdiagonals and subdiagonals into account, a n dimensional matrix, has n×(n-1) diagonals. We can assign this by mirroring one or more dimensions.

这篇关于用python替换2D数组的对角线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆