Reputation: 9
i'm creating a program that get the neighbors of nodes in graph from edgelist but the problem is he show me this error
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)
File "C:\Users\Toshiba\Anaconda2\lib\site-packages\networkx\classes\graph.py", line 1130, in neighbors
raise NetworkXError("The node %s is not in the graph." % (n,))
NetworkXError: The node 1 is not in the graph.
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)
and the content of the file 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
Upvotes: 1
Views: 7259
Reputation: 35
i got the same error ,when i tried to print nodes from the graph created by the code script mentioned below:
'A =os.path.realpath("last_exuction.txt")
fh=open(A, 'rb')
G=nx.read_edgelist(fh)
fh.close()'
but when I this code snippet:
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)'
it may resolve this Networkx error problem.
Upvotes: 0
Reputation: 23887
Node 1
is not in your graph. I suspect that Node '1'
is. That is, the string '1'
rather than the integer 1
is in your graph.
This is because when you read the file in, it interprets everything as strings. The documentation shows the optional arguments: read_edgelist(path, comments='#', delimiter=None, create_using=None, nodetype=None, data=True, edgetype=None, encoding='utf-8')
. Notice the optional argument nodetype
. The documentation says:
nodetype (int, float, str, Python type, optional) – Convert node data from strings to specified type
So do your call as
G=nx.read_edgelist(fh, nodetype = int)
Upvotes: 1