python - 如何逐行遍历一个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
,您可以看到应该是第一行的内容已作为第一列输入,依此类推。
我该如何纠正?
解决方案
推荐阅读
- javascript - 如何创建一个对象数组,其中每个对象有 4 个值?
- javascript - NextJS 无法使用使用 SASS 和 CSS 的库
- html - 如何使用 :hover 为覆盖的 div 设置动画?我需要 JS 还是可以在 CSS 中完成?
- powerbi - 如何使用 power bi 为图形可视化创建周开始数据和周结束日期列?
- react-native - 键盘不会关闭?
- javascript - “点击”事件不适用于链接图像
- python - 如何避免通过条件循环下载相同的文件?
- python-3.x - 连接两个熊猫数据框列
- node.js - NodeJS 中的分布式计算 - 数学表达式
- r - R获取具有相同但较小的其他列值的唯一列值的计数