msmazh
msmazh

Reputation: 895

Number of components of a node in Networkx

How can I compute the number of connected components surrounding a given node in a network?

Example: suppose A is connected to B. A is also connected to C and D, and C and D are connected to each other as well. In this case, node A has 2 connected components including [B] and [C,D].

Upvotes: 1

Views: 1420

Answers (1)

Arya McCarthy
Arya McCarthy

Reputation: 8829

I believe I understand your intent now.

Let's use Padgett's Florentine families as a model.

Florentine families graph

Here, of the neighbors of the Medici node, only Ridolfi and Tornabuoni are neighbors of each other.

# Setup
import networkx as nx
G = nx.florentine_families_graph()  # Or whatever else your graph is.

# Computation
node_id = 'Medici'  # Your nodes are probably identified by a number.
ego = nx.ego_graph(G, n=node_id, center=False)
components = nx.connected_components(ego)
for c in components:
    print(c)
# {'Acciaiuoli'}
# {'Ridolfi', 'Tornabuoni'}
# {'Albizzi'}
# {'Salviati'}
# {'Barbadori'}

The ego graph is all immediate neighbors of a node n. center=False excludes n from that graph. From there, we find the components.

Upvotes: 2

Related Questions