【问题标题】:how to fix the problem of the node is not in graph如何解决节点不在图中的问题
【发布时间】:2019-08-18 02:57:33
【问题描述】:

我正在创建一个程序,从边缘列表中获取图中节点的邻居,但问题是他向我展示了这个错误

A=nx.all_neighbors(G,1)

File"C:\Users\Toshiba\Anaconda2\lib\sitepackages\networkx\classes\function.py", line 838, in all_neighbors  values = graph.neighbors(node)

文件“C:\Users\Toshiba\Anaconda2\lib\site-packages\networkx\classes\graph.py”,第 1130 行,在邻居中

raise NetworkXError("节点 %s 不在图中。" % (n,))

NetworkXError:节点 1 不在图中。

import networkx as nx
import os


A =os.path.realpath("last_exuction.txt")
fh=open(A, 'rb')
G=nx.read_edgelist(fh)
fh.close()

A=nx.all_neighbors(G,1)

以及文件last_exuction.txt的内容

2 1
3 1
3 2
4 1
4 2
4 3
5 1
6 1
7 1
7 5
7 6
8 1
8 2
8 3
8 4
9 1
9 3
10 3
11 1
11 5
11 6
12 1
13 1
13 4
14 1
14 2
14 3
14 4
17 6
17 7
18 1
18 2
20 1
20 2
22 1
22 2
26 24
26 25
28 3
28 24
28 25
29 3
30 24
30 27
31 2
31 9
32 1
32 25
32 26
32 29
33 3
33 9
33 15
33 16
33 19
33 21
33 23
33 24
33 30
33 31
33 32
34 9
34 10
34 14
34 15
34 16
34 19
34 20
34 21
34 23
34 24
34 27
34 28
34 29
34 30
34 31
34 32
34 33

【问题讨论】:

    标签: python graph networkx


    【解决方案1】:

    节点1 不在您的图表中。我怀疑节点'1' 是。也就是说,字符串'1' 而不是整数1 在您的图表中。

    这是因为当您读入文件时,它会将所有内容都解释为字符串。 documentation 显示可选参数:read_edgelist(path, comments='#', delimiter=None, create_using=None, nodetype=None, data=True, edgetype=None, encoding='utf-8')。注意可选参数nodetype。文档说:

    nodetype (int, float, str, Python type, optional) – 转换节点数据 从字符串到指定类型

    你的电话也是

    G=nx.read_edgelist(fh, nodetype = int)
    

    【讨论】:

      【解决方案2】:

      当我尝试从下面提到的代码脚本创建的图表中打印节点时,我遇到了同样的错误:

         'A =os.path.realpath("last_exuction.txt")
         fh=open(A, 'rb')
         G=nx.read_edgelist(fh)
         fh.close()'
      

      但是当我这段代码 sn-p:

          from tqdm import tqdm
          import csv
          with open('lastfm_asia_edges.csv', 'r') as f:
            data = csv.reader(f)
            headers = next(data)
            for row in tqdm(data):
                G.add_node(row[0]) #superhero in first column
                G.add_node(row[1]) #superhero in second column
                if G.has_edge(row[0], row[1]):
      
               # edge already exists, increase weight by one
                G[row[0]][row[1]]['weight'] += 1
                else:
               # add new edge with weight 1
                G.add_edge(row[0], row[1], weight = 1)'
      

      它可能会解决这个 Networkx 错误问题。

      【讨论】:

        猜你喜欢
        • 2020-06-28
        • 1970-01-01
        • 2015-06-09
        • 1970-01-01
        • 2021-09-17
        • 1970-01-01
        • 1970-01-01
        • 2012-11-19
        • 2019-07-18
        相关资源
        最近更新 更多