Guram Keretchashvili
Guram Keretchashvili

Reputation: 47

how to find degree centrality of nodes in the community partitions structure using networkX?

I have used partition = community.best_partition(test_graph) to get partitions from the networkX graph. I got a dictionary like this:

{node0: 0,
 node1: 0,
 node2: 0,
 node3: 1,
 node4: 1,
 node5: 1,
 node5: 2,
 node6: 2,
...
}

in which keys are the nodes and values are community numbers. I want to find most degree centrality nodes in each community number. For example, in this case: in the community 1: I have 3 nodes, which of them have highest degree?

Upvotes: 2

Views: 1126

Answers (1)

CDJB
CDJB

Reputation: 14516

If I understand this question correctly, the following code should give what you're after:

Code:

import community
import networkx as nx

# Generate test graph
G = nx.erdos_renyi_graph(30, 0.05)

# Relabel nodes
G = nx.relabel_nodes(G, {i: f"node_{i}" for i in G.nodes})

# Compute partition
partition = community.best_partition(G)

# Get a set of the communities
communities = set(partition.values())

# Create a dictionary mapping community number to nodes within that community
communities_dict = {c: [k for k, v in partition.items() if v == c] for c in communities}

# Filter that dictionary to map community to the node of highest degree within the community
highest_degree = {k: max(v, key=lambda x: G.degree(x)) for k, v in communities_dict.items()}

Output:

>>> partition
{'node_0': 0,
 'node_1': 1,
 'node_2': 2,
 'node_3': 3,
 ...
 'node_25': 3,
 'node_26': 11,
 'node_27': 12,
 'node_28': 10,
 'node_29': 10}
>>> highest_degree
{0: 'node_0',
 1: 'node_1',
 2: 'node_2',
 3: 'node_3',
 4: 'node_19',
 5: 'node_9',
 6: 'node_10',
 7: 'node_11',
 8: 'node_13',
 9: 'node_21',
 10: 'node_24',
 11: 'node_26',
 12: 'node_27'}

Upvotes: 1

Related Questions