如何提取非方形numpy数组的下/上三角形?

2024-10-01 04:52:57 发布

您现在位置:Python中文网/ 问答频道 /正文

因此基本上我有一个数组subslope,由以下内容组成:

import numpy as np
import matplotlib.pyplot as plt

slp = 1501.66*(np.ones((1000,1000), dtype=np.float32))
vsub = 2000*(np.ones((1000,1000), dtype=np.float32))

slope = np.triu(slp)
slope2 = np.tril(vsub, k=-1)
subslope = slope + slope2

这是视觉表现:

enter image description here

您可以看到分隔数组两部分的对角线,上面部分的值为1501.66,对角线下面的值为2000。但是,当我更改维度时,列数明显大于行数,如下所示:

slp = 1501.66*(np.ones((1000,2000), dtype=np.float32))
vsub = 2000*(np.ones((1000,2000), dtype=np.float32))

我们得到以下结果:

enter image description here

我想要的是对角线从数组的上角到下角,如下所示:

enter image description here

我怎样才能做到这一点


Tags: importnumpymatplotlibasnpones数组slope
2条回答

要生成数组,请填充nR行和nC列:

  • 在带有valDiag的对角线处
  • 在对角线上使用valUpper
  • 对角线下方带有valLower

您可以使用以下功能:

def genDiag(nR, nC, valUpper, valDiag, valLower):
    slope = nC / nR
    tbl = np.full((nR, nC), valDiag, dtype=float)
    for r in range(nR):
        tbl[r, 0 : int(round(slope * r, 0))] = valLower
        tbl[r, int(round(slope * (r + 1), 0)) : nC] = valUpper
    return tbl

要测试它,请在较小的数字上运行:

res = genDiag(8, 14, 15.1, 0, 20.2)
print(res)

结果是:

[[ 0.   0.  15.1 15.1 15.1 15.1 15.1 15.1 15.1 15.1 15.1 15.1 15.1 15.1]
 [20.2 20.2  0.   0.  15.1 15.1 15.1 15.1 15.1 15.1 15.1 15.1 15.1 15.1]
 [20.2 20.2 20.2 20.2  0.  15.1 15.1 15.1 15.1 15.1 15.1 15.1 15.1 15.1]
 [20.2 20.2 20.2 20.2 20.2  0.   0.  15.1 15.1 15.1 15.1 15.1 15.1 15.1]
 [20.2 20.2 20.2 20.2 20.2 20.2 20.2  0.   0.  15.1 15.1 15.1 15.1 15.1]
 [20.2 20.2 20.2 20.2 20.2 20.2 20.2 20.2 20.2  0.  15.1 15.1 15.1 15.1]
 [20.2 20.2 20.2 20.2 20.2 20.2 20.2 20.2 20.2 20.2  0.   0.  15.1 15.1]
 [20.2 20.2 20.2 20.2 20.2 20.2 20.2 20.2 20.2 20.2 20.2 20.2  0.   0. ]]

如果您希望这张桌子没有单独填充对角线, 首先决定是否填充对角线元素 使用“上限”或“下限”值,然后将所选值作为valDiag传递

可以使用^{}创建布尔掩码:

import numpy as np
import matplotlib.pyplot as plt

shape = (1000, 2000)
i,j = np.indices(shape)
m = np.ceil(i <= j*shape[0]/shape[1]).astype(bool)

subslope = np.empty(shape, np.float32)
subslope[m] = 1501.66
subslope[~m] = 2000

plt.imshow(subslope)

enter image description here

相关问题 更多 >