首页 > 解决方案 > 如何逐行遍历一个numpy矩阵?

问题描述

如果我有一个 numpy 数组

[[ 0 -2 -4 -6]
 [-2 -3 -5 -7]
 [-4  0 -2 -4]
 [-6 -2 -3 -5]]

我如何逐行访问这个称为 mymatrix 的 numpy 数组的每个元素,例如,如果数组通过双 for 循环遍历,mymatrix[x][y]=the element that is traversed我会得到0,-2,-4,-6,-2,-3,-5,-7,-4,0,-2,-4,-6,-2等等

编辑:

当我从下面遵循双循环方法时,这就是我得到的

for row in range(scorematrix.shape[0]):
    for col in range(scorematrix.shape[1]):
        final=[]
        if row==0 and col==0:
            scorematrix[row][col]=0
            continue
        elif row==0:
            scorematrix[row][col]=col+(col*-3)
            continue
        elif col==0:
            scorematrix[row][col]=row+(row*-3)
            continue
        elif seq1[row]=="A" and seq2[col]=="A":
            result=4
        elif seq1[row]=="C" and seq2[col]=="C":
            result=3
        elif seq1[row]=="G" and seq2[col]=="G":
            result=2
        elif seq1[row]=="T" and seq2[col]=="T":
            result=1
        elif seq1[row]!=seq2[col]:
            result=-3
        print(scorematrix)
        firstelement=result+scorematrix[row-1,col-1]
        final.append(firstelement)
        secondelement=scorematrix[row-1,col]-2
        final.append(secondelement)
        thirdelement=scorematrix[row,col-1]-2
        final.append(thirdelement)
        themax=max(final)
        index=[k for k, j in enumerate(final) if j == themax]
        listofc.append(index)

        scorematrix[row][col]=themax

我的问题需要的主要内容是前两行和最后一行,其余的只是一些计算。我要输出[[ 0 -2 -4 -6] [-2 -3 -5 -7] [-4 0 -2 -4] [-6 -2 -3 -5]]

的矩阵是 但是我得到的矩阵是

[[ 0 -2 -4 -6] [-2 -3 0 -2] [-4 -5 -2 -3] [-6 -7 -4 -5]] 如果您忽略带有 的行和列0,-2,-4,-6,您可以看到应该是第一行的内容已作为第一列输入,依此类推。

我该如何纠正?

标签: pythonarraysnumpy

解决方案


推荐阅读