使用Numpy向矩阵的缺失值添加零

2024-06-02 06:29:42 发布

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

我使用Numpy(Python)为for循环的第I次迭代获得两个矩阵L和R的几个值,预期维数为2200x88。 有些矩阵的元素较少,例如1200x55,在这些情况下,我必须给矩阵加上0,以使它的维数为2200x88。我创建了以下程序来解决这个问题:

        for line in infile:
        line = line.strip()
        #more code here, l is matrix 1 of the ith iteration, r is matrix 2 of ith iteration 
ls1, ls2=l.shape
rs1, rs2= r.shape
            if ls1 != 2200 | ls2 != 88:
                l.resize((2200, 88), refcheck=False)
            if rs1 != 2200 | rs2 != 88:
                r.resize((2200, 88), refcheck=False)
            var = np.concatenate((l, r), axis=0).reshape(1,387200)

问题在于,当检测到矩阵R或L的尺寸不为2200×88时,I将获得以下误差:

^{pr2}$

有人对如何解决这个问题有什么建议吗?在

谢谢。在


Tags: offorifisline矩阵matrixshape
1条回答
网友
1楼 · 发布于 2024-06-02 06:29:42

由于l是一个矩阵,l[0]是该矩阵的一个条带,一个数组。在

本部分:

if l[0] != 2200 | l[1] != 88

正在导致您的错误,因为您正在尝试“或”两个数组。在

所以不是

^{pr2}$

考虑:

 if l.shape != (2200, 88):
     l.resize((2200, 88), refcheck=False)
 if r.shape != (2200, 88):
     r.resize((2200, 88), refcheck=False)

相关问题 更多 >