Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the data for the edge between two nodes?

I want to get the edge between two nodes in a networkx graph. More specifically, I want to get some data associated with this edge. I know a priori that these two nodes are linked. Is there a function to do this?

like image 246
becko Avatar asked Feb 09 '16 00:02

becko


People also ask

How do you interpret whether two nodes are adjacent or not?

An edge is incident on the two nodes it connects. Any two nodes connected by an edge or any two edges connected by a node are said to be adjacent.

How to find a path between two nodes in a graph?

Approach: Either Breadth First Search (BFS) or Depth First Search (DFS) can be used to find path between two vertices. Take the first vertex as a source in BFS (or DFS), follow the standard BFS (or DFS). If the second vertex is found in our traversal, then return true else return false.

How do you find the number of edges between two nodes in a tree?

One simple option is to do a depth-first search starting at one of the nodes until you reach the other node. You can then look at the path that was taken from the first node to the second, which must be the unique path between those nodes, and then count how many edges are in that path.


1 Answers

The edge data are stored in a dictionary. To access that dictionary, use get_edge_data().

import networkx as nx
G=nx.Graph()
G.add_edge(1,2, weight=5)
G.get_edge_data(1,2)
> {'weight': 5}

If you want to iterate through all the edges you can use G.edges(data=True)

H = nx.Graph()
H.add_edge(2, 3, color = 'red')
H.add_edge(1, 2, weight = 4)
for u,v,data in H.edges(data=True):
    print(u, v, data)
> 1 2 {'weight': 4}
> 2 3 {'color': 'red'}
like image 102
Joel Avatar answered Oct 13 '22 05:10

Joel