在Networkx Python中查找最高中心性度量



我正在尝试编写一个函数,该函数采用图形并返回一个数据帧,第一列是具有最高中心性度量的节点列表,第二列是最高中心性度量的值。

下面附的是我的代码,我不知道如何完成它。如何在没有其他函数的情况下找到最高中心性?

def summary(G):
df = pd.DataFrame() 
dc=nx.degree_centrality(G) 
cc=nx.closeness_centrality(G) 
bc=nx.closeness_centrality(G) 
df['Nodes with the highest centrality measure']= #addcodehere
df['Value of the highest centrality measure']= #addcodehere
return df.set_index(['dc','cc','bc'])

你可以这样做:

# Imports and graph creation (you don't need them in your function)
import networkx as nx
import pandas as pd
G = nx.fast_gnp_random_graph(20, 0.1)

创建中心性字典:

cc = nx.closeness_centrality(G)

cc看起来像这样:

{0: 0.28692699490662144,
1: 0.26953748006379585,
2: 0.32943469785575047,
3: 0.28692699490662144,
4: 0.30671506352087113,
5: 0.26953748006379585,
...

然后使用from_dict创建数据帧:

df = pd.DataFrame.from_dict({
'node': list(cc.keys()),
'centrality': list(cc.values())
})

df看起来像这样:

centrality  node
0   0.286927    0
1   0.269537    1
2   0.329435    2
3   0.286927    3
4   0.306715    4
5   0.269537    5
...

然后按中心性降序排序:

df = df.sort_values('centrality', ascending=False)

所以df看起来像这样:

centrality  node
12  0.404306    12
7   0.386728    7
2   0.329435    2
4   0.306715    4
0   0.286927    0
...

并返回结果。完整代码为:

def summary(G):
cc = nx.closeness_centrality(G)
df = pd.DataFrame.from_dict({
'node': list(cc.keys()),
'centrality': list(cc.values())
})
return df.sort_values('centrality', ascending=False)

最新更新