Networkx:列出每个节点的中心性的最佳方法是什么?

时间:2015-03-04 19:04:39

标签: python csv networkx

假设您有一个小图表,并希望为干净的csv中的每个节点获得一些中心。

import networkx as nx
import csv
# Cast the graph
G=nx.Graph()
G.add_nodes_from([1,2,3,4,5,6])
G.add_edges_from([(1,2),(1,3),(2,3),(2,5),(2,6),(6,4)])
node_list = G.nodes()
# Compute dictionaries with centralities
betweenness_centr = nx.betweenness_centrality(G)
eigenvector_centr = nx.eigenvector_centrality_numpy(G)
clustering_centr = nx.clustering(G)

现在以什么方式继续?合并词典?节点属性?阵列

以下是带有组合词典的尝试

comb_dict = dict([(node, [eigenvector_centr[node], betweenness_centr[node]]) for node in node_list])
with open('some_file.csv', 'wb') as f:
    outfileWriter = csv.DictWriter(f, fieldnames=comb_dict.keys())
    outfileWriter.writeheader()
    outfileWriter.writerow(comb_dict)

但是some_file.csv自然将节点名称作为标题:

1   2   3   4   5   6
[0.4553183188774393, 0.0]   [0.6282837873950563, 0.8]   [0.4553183188774396, 0.0]   [0.13471441935354073, 0.0]  [0.2639983036196953, 0.0]   [0.3206038995238985, 0.4]

但它应该是

node    betweenness_centr   eigenvector_centr
1   0.4553183188774393  0.0
2   0.6282837873950563  0.8
#and so forth

1 个答案:

答案 0 :(得分:0)

如果没有CSV编写器,你可以这样做。

with open('some_file.csv', 'wb') as f:
    for n in G:
        f.write("%s %f %f\n"%(n,betweenness_centr[n],eigenvector_centr[n]))

$ cat some_file.csv 
1 0.000000 0.455318
2 0.800000 0.628284
3 0.000000 0.455318
4 0.000000 0.134714
5 0.000000 0.263998
6 0.400000 0.320604

跟进:

标签是\ t,你可以在第一行写下你想要的任何内容

with open('some_file.csv', 'wb') as f:
    f.write('node\tbetweenness\teigenvector\n')
    for n in G:
        f.write("%s\t%f\t%f\n"%(n,betweenness_centr[n],eigenvector_centr[n]))

$ cat some_file.csv 
node    betweenness eigenvector
1   0.000000    0.455318
2   0.800000    0.628284
3   0.000000    0.455318
4   0.000000    0.134714
5   0.000000    0.263998
6   0.400000    0.320604

使用csv writer:

with open('some_file.csv', 'wb') as f:
    outfileWriter = csv.writer(f,delimiter='\t')
    for n in G:
        outfileWriter.writerow([n,betweenness_centr[n],eigenvector_centr[n]])