masti
masti

Reputation: 77

How do I get nodes from the specific edge in the networkx?

I want to compare nodes of different edges in the graph. How can I get the nodes(n1 and n2) from the edge(n1,n2)?

Upvotes: 2

Views: 9057

Answers (2)

Chris
Chris

Reputation: 31186

The answer to what I think was the intended question is:

graph = networkx.read_graphml('some_fully_loaded_graph.graphml')
edge0 = list(graph.edges(data=True))[0]

subgraph = graph.edge_subgraph([edge0[:2]])
nodes0 = list(subgraph.nodes(data=True))

Upvotes: 0

ire_and_curses
ire_and_curses

Reputation: 70142

An edge in NetworkX is defined by its nodes, so I'm not really sure what you're asking here. A specific edge in the graph is just a tuple of nodes, with an optional weighting.

import networkx as nx
g = nx.Graph()
g.add_edge(1,2)
g.add_edge(2,3)
g.edges()

gives

[(1, 2), (2, 3)]

As you can see, the list of edges explicitly provides the nodes of each edge.

Update: Does this do what you want?

#!/usr/bin/python

import networkx as nx
import random

g = nx.Graph()
g.add_edges_from([(1,2),(2,3),(1,4),(2,5)])

random_edge = random.choice(g.edges())

print 'Randomly selected edge is:', random_edge
print 'Nodes are', random_edge[0], 'and', random_edge[1]

Upvotes: 4

Related Questions