NetworkX - 将结果写入CSV以进行多项措施

时间:2014-05-20 19:13:27

标签: python csv networkx

我正在使用NetworkX为大型网络计算4个独立的中心度量标准,现在我想将结果写入CSV文件。我不想为4个指标中的每一个编写单个CSV文件,而是希望具有如下内容:

Id, degree, between, close, eigen

1, 0.4, 0.0, 0.5, 0.45

2, 0.4, 0.0, 0.5, 0.45

3, 0.6, 0.6, 0.71, 0.58

4, 0.6, 0.7, 0.71, 0.47

5, 0.2, 0.0, 0.45, 0.18

6, 0.2, 0.0, 0.45, 0.18

以下是我的代码,以展示我到目前为止所做的工作:

import networkx as nx
G = nx.Graph()

# add nodes and edges
G.add_edges_from([(1,2),(1,3),(2,3),(3,4),(4,5),(4,6)])

# calculate centrality metrics    
degree = nx.degree_centrality(G)
between = nx.betweenness_centrality(G)
close = nx.closeness_centrality(G)
eigen = nx.eigenvector_centrality(G)

2 个答案:

答案 0 :(得分:1)

您可以并行迭代字典。

首先,将每个字典转换为(key, value)元组列表,按键排序:

degree = sorted(degree.items())
between = sorted(between.items())
close = sorted(close.items())
eigen = sorted(eigen.items())

接下来,创建一个并行迭代器:

p = zip(degree, between, close, eigen)

现在,p是:

[((1, 0.4), (1, 0.0), (1, 0.5), (1, 0.45698629803118)),
 ((2, 0.4), (2, 0.0), (2, 0.5), (2, 0.45698629803118)),
 ((3, 0.6000000000000001),
  (3, 0.6000000000000001),
  (3, 0.7142857142857143),
  (3, 0.5842167062067959)),
 ((4, 0.6000000000000001),
  (4, 0.7000000000000001),
  (4, 0.7142857142857143),
  (4, 0.4171170012545873)),
 ((5, 0.2), (5, 0.0), (5, 0.45454545454545453), (5, 0.1830727919118216)),
 ((6, 0.2), (6, 0.0), (6, 0.45454545454545453), (6, 0.1830727919118216))]

现在,迭代p的每一行:

for row in p:
    this_keys, this_values = zip(*row)
    assert len(set(this_keys)) == 1 # make sure we got what we expected
    this_key = this_keys[0]
    # Now, this_key is the key and this_values is a tuple of values
    print this_key, ['%.2f' % v for v in this_values]

输出结果为:

1 ['0.40', '0.00', '0.50', '0.46']
2 ['0.40', '0.00', '0.50', '0.46']
3 ['0.60', '0.60', '0.71', '0.58']
4 ['0.60', '0.70', '0.71', '0.42']
5 ['0.20', '0.00', '0.45', '0.18']
6 ['0.20', '0.00', '0.45', '0.18']

现在,您可以将它们保存到csv文件,而不是打印。

答案 1 :(得分:1)

我找到了一个简单的答案,它将在一行上打印节点的多个度量结果。

## calculate centrality metrics:
degree = nx.degree_centrality(G)
between = nx.betweenness_centrality(G)
close = nx.closeness_centrality(G)
eigen = nx.eigenvector_centrality(G)

## print the multiple centrality metrics to a single line for each node:
for n in G:
    print ("%d, %f, %f, %f, %f"%(n, degree[n], between[n], close[n], eigen[n]))