Python循环遍历文本并设置numpy数组索引

2024-06-26 13:58:59 发布

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

给定一个包含由逗号和分号分隔的矩阵行和列的文本块,我想解析文本并设置numpy数组的索引。下面是用变量“matrixText”表示基文本的代码。你知道吗

我首先创建矩阵,然后用分号和逗号分割文本。我循环浏览拆分的文本并设置每个索引。但是在文本中。。。你知道吗

1,2,3;4,5,6;7,8,9

我知道结果了

7,7,7;8,8,8;9,9,9

temp1=matrixText.split(';')
temp2=temp1[0].split(',')
rows=len(temp1)
columns=len(temp2)
rA=np.zeros((rows, columns))
arrayText=matrixText.split(';')
rowText=range(len(arrayText))
for rowIndex, rowItem in enumerate(arrayText):
    rowText[rowIndex]=arrayText[rowIndex].split(',')
    for colIndex, colItem in enumerate(rowText[rowIndex]):
        rA[[rowIndex, colIndex]]=rowText[rowIndex][colIndex]

我认为通过设置每个索引,我可以避免任何引用复制的问题。你知道吗

为了提供更多信息,在第一次迭代中,将0,0索引设置为1,然后输出为1,1,1;0,0,0;0,0,0,我无法计算,因为在numpy数组中设置一个索引会设置三个。你知道吗

在第二次迭代中,索引0-1设置为2,结果为2,2,2;2,2,2;0,0,0

第三次迭代将0-2设置为3,但结果是3,3,3;2,2,2;3,3,3

有什么建议吗?你知道吗


Tags: 文本numpylen矩阵数组rowssplit逗号
3条回答

您可以(ab-)使用matrix构造函数和A属性

np.matrix('1,2,3;4,5,6;7,8,9').A

输出:

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
matrixText = '1,2,3;4,5,6;7,8,9'
temp1=matrixText.split(';')
temp2=temp1[0].split(',')
rows=len(temp1)
columns=len(temp2)
rA=np.empty((rows, columns),dtype=np.int)
for n, line in enumerate(temp1):         
    rA[n,:]=line.split(',')

使用嵌套的list-comprehension

定义了:

s = "1,2,3;4,5,6;7,8,9"

我们可以用一个漂亮的one-liner

np.array([[int(c) for c in r.split(",")] for r in s.split(";")])

它将给出以下array

array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

相关问题 更多 >