How to extract random nodes from networkx graph?

Lora Kostova picture Lora Kostova · Nov 5, 2014 · Viewed 9.7k times · Source

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 to each of them and their edges. I suppose I can do that with "np.random.choice" but I still can't get any results.

Answer

chishaku picture chishaku · Nov 5, 2014
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 possible duplicate: how to select two nodes (pairs of nodes) randomly from a graph that are NOT connected, Python, networkx