import networkx as nx
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib notebook
G = nx.karate_club_graph()
G = nx.convert_node_labels_to_integers(G, first_label=1)
plt.figure()
nx.draw_networkx(G)
<IPython.core.display.Javascript object>
deg_cent = nx.degree_centrality(G)
print(deg_cent[1])
0.48484848484848486
print('节点1的度:', nx.degree(G, 1))
print('网络节点个数:', len(nx.nodes(G)))
print('节点1的度中心性:{} / ({}-1) = {}'.format(nx.degree(G, 1),
len(nx.nodes(G)),
nx.degree(G, 1) / (len(nx.nodes(G)) - 1)))
节点1的度: 16
网络节点个数: 34
节点1的度中心性:16 / (34-1) = 0.48484848484848486
close_cent = nx.closeness_centrality(G)
print(close_cent)
{1: 0.5689655172413793, 2: 0.4852941176470588, 3: 0.559322033898305, 4: 0.4647887323943662, 5: 0.3793103448275862, 6: 0.38372093023255816, 7: 0.38372093023255816, 8: 0.44, 9: 0.515625, 10: 0.4342105263157895, 11: 0.3793103448275862, 12: 0.36666666666666664, 13: 0.3707865168539326, 14: 0.515625, 15: 0.3707865168539326, 16: 0.3707865168539326, 17: 0.28448275862068967, 18: 0.375, 19: 0.3707865168539326, 20: 0.5, 21: 0.3707865168539326, 22: 0.375, 23: 0.3707865168539326, 24: 0.39285714285714285, 25: 0.375, 26: 0.375, 27: 0.3626373626373626, 28: 0.4583333333333333, 29: 0.4520547945205479, 30: 0.38372093023255816, 31: 0.4583333333333333, 32: 0.5409836065573771, 33: 0.515625, 34: 0.55}
print('节点1的接近中心性:', close_cent[1])
节点1的接近中心性: 0.5689655172413793
print('网络节点个数:', len(nx.nodes(G)))
print('节点1与其他节点的最短路径和:', sum(nx.shortest_path_length(G, 1).values()))
网络节点个数: 34
节点1与其他节点的最短路径和: 58
(34 - 1) / 58
0.5689655172413793
btwn_cent = nx.betweenness_centrality(G, normalized=True, endpoints=False)
import operator
# 按字典的值排序
sorted(btwn_cent.items(), key=operator.itemgetter(1), reverse=True)[:5]
[(1, 0.43763528138528146),
(34, 0.30407497594997596),
(33, 0.14524711399711399),
(3, 0.14365680615680618),
(32, 0.13827561327561325)]
nx.pagerank(G)
{1: 0.09700181758983709,
2: 0.05287839103742701,
3: 0.057078423047636745,
4: 0.03586064322306479,
5: 0.021979406974834498,
6: 0.02911334166344221,
7: 0.02911334166344221,
8: 0.024490758039509182,
9: 0.029765339186167028,
10: 0.014308950284462801,
11: 0.021979406974834498,
12: 0.009564916863537148,
13: 0.014645186487916191,
14: 0.029536314977202986,
15: 0.014535161524273825,
16: 0.014535161524273825,
17: 0.016785378110253487,
18: 0.014558859774243493,
19: 0.014535161524273825,
20: 0.019604416711937293,
21: 0.014535161524273825,
22: 0.014558859774243493,
23: 0.014535161524273825,
24: 0.03152091531163228,
25: 0.021075455001162945,
26: 0.021005628174745786,
27: 0.015043395360629753,
28: 0.025638803528350497,
29: 0.01957296050943854,
30: 0.02628726283711208,
31: 0.02458933653429248,
32: 0.03715663592267942,
33: 0.07169213006588289,
34: 0.1009179167487121}