Reputation: 21
I have a distance matrix as shown below:
[A B C D....
A 0 NaN 2 3
B NaN 0 2 5
C 3 1 0 NaN
D 4 18 NaN 0
...]
To calculate centrality measures, I draw a network but it returns the same numbers for each of the centrality measures (Between, closeness, degree, etc.).
Below is my code:
(Domain: A, B, C, D, ...)
ser3 = df['Domain'].unique()
G_weighted = nx.Graph()
for x in ser3:
if(x is None):continue
for y in ser3:
ind=dist_matrix[x][y]
print(ind)
if (ind is None):continue
if (ind>0): G_weighted.add_edge(x,y,weight=ind)
nx.betweenness_centrality(G)
[Out]:
{'A': 0.0, 'B': 0.0, 'C': 0.0, 'D': 0.0, ....}
Can someone help me figure this out? Thanks a lot in advance...
Upvotes: 2
Views: 726
Reputation: 88226
I'm not getting quite the same as you. Normally you get a betweenness centrality of zero for all nodes if you have a complete graph, i.e a graph where all pairs of nodes are connected. But that doesn't seem to be your case (unless you are not correctly ignoring those NaNs, that would explain it).
Assuming the adjacency matrix is a dataframe, using your sample matrix I'm getting:
G = nx.from_pandas_adjacency(df)
edges_rem = []
for edge in G.edges(data=True):
if np.isnan(edge[2]['weight']):
edges_rem.append(edge[:2])
G.remove_edges_from(edges_rem)
G_weighted.edges(data=True)
# EdgeDataView([('A', 'C', {'weight': 3.0}), ('A', 'D', {'weight': 4.0}),
# ('C', 'B', {'weight': 1.0}), ('D', 'B', {'weight': 18.0})])
nx.betweenness_centrality(G_weighted)
{'A': 0.16666666666666666,
'B': 0.16666666666666666,
'C': 0.16666666666666666,
'D': 0.16666666666666666}
Upvotes: 1