How to extract random nodes from networkx graph?

How to extract random nodes from networkx graph? I have a map in the form of a networkx graph, and I have to extract 5 random nodes from it and get the data associated with each of them and their edges. I suppose I can do this with "np.random.choice", but I still can’t get any results.

+4
source share
1 answer
import networkx as nx
from random import choice

g = nx.Graph()
g.add_edge(1,2)
g.add_edge(1,3)
g.add_edge(1,4)
g.add_edge(1,5)
g.add_edge(5,6)

random_node = choice(g.nodes())

From a possible duplicate: randomly select two nodes (pairs of nodes) from the graph that are NOT connected, Python, networkx

+2
source

All Articles