如何从一个csvfile读取多个矩阵?

2024-03-29 12:24:00 发布

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

我正试图从一个文本文件中加载多个矩阵。你知道吗

我想从同一个文件中读取几个矩阵,以便在网络中绘制它们。当输入文件只包含一个矩阵时,我设法做到了这一点,但当它包含许多矩阵时,我不知道如何做到这一点。 输入文件看起来像这样,只是它大了一点:

x [*,*,0]
:    0   1   2   3   4   :=
0    .   0   0   1   1   
1    1   .   0   0   0   
2    1   0   .   0   0   
3    0   0   0   .   0   
4    0   0   0   0   .   

我的代码是这样的:

infile = "testfile.sol"
edges = []
import pandas as pd
colNames = [i for i in range(11)]
df = pd.read_csv('testfile.sol', sep=' ', skipinitialspace=True, index_col=0,names=colNames, skiprows=[0, 1])

for i in range(len(df)):
    for j in range(len(df)):
        if df[i][j] == "1":
            index_i = i
            index_j = j
            edge = (i,j)
            edges.append(edge)
import networkx as nx
G = nx.Graph()
G.add_edges_from(edges)

这是可行的,但我的输入文件中有几个这样的文件:

x [*,*,0]
:    0   1   2   3   4   :=
0    .   0   0   1   1   
1    1   .   0   0   0   
2    1   0   .   0   0   
3    0   0   0   .   0   
4    0   0   0   0   .   

x [*,*,1]
:    0   1   2   3   4   :=
0    .   0   0   1   0   
1    1   .   0   0   0   
2    1   0   .   0   1   
3    0   0   0   .   0   
4    0   0   0   0   .   

如何阅读所有这些内容,并列出边0、边1等等?你知道吗


Tags: 文件inimportdfforindexlenas