我使用NetworkX来计算网络的某些中心度量标准。如何以表格格式将这些结果保存到csv文件中?我只能在终端打印结果。
G = nx.Graph()
G.add_edges_from([(1,2),(1,3),(2,3),(3,4),(4,5),(4,6)])
DEGREE_CENTRALITY = nx.degree_centrality(G)
EIGENVECTOR = nx.eigenvector_centrality(G)
KATZ = nx.katz_centrality_numpy(G)
CLOSENESS_CENTRALITY = nx.closeness_centrality(G)
BETWEENNESS_CENTRALITY = nx.betweenness_centrality(G)
CLUSTCOEF = nx.clustering(G)
在终端中打印结果:
for n in G: print ("%s, %f, %f, %f, %f, %f, %f"%(n, DEGREE_CENTRALITY[n],
EIGENVECTOR[n], KATZ[n], CLOSENESS_CENTRALITY[n], BETWEENNESS_CENTRALITY[n],
CLUSTCOEF[n]))
...
1, 0.400000, 0.456986, 0.408764, 0.500000, 0.000000, 1.000000
2, 0.400000, 0.456986, 0.408764, 0.500000, 0.000000, 1.000000
3, 0.600000, 0.584217, 0.448883, 0.714286, 0.600000, 0.333333
4, 0.600000, 0.417117, 0.441314, 0.714286, 0.700000, 0.000000
5, 0.200000, 0.183073, 0.367131, 0.454545, 0.000000, 0.000000
6, 0.200000, 0.183073, 0.367131, 0.454545, 0.000000, 0.000000
答案 0 :(得分:1)
您可以将其粘贴到pandas数据框中并使用to_csv
方法。
import pandas as pd
import networkx as nx
G = nx.Graph()
G.add_edges_from([(1,2),(1,3),(2,3),(3,4),(4,5),(4,6)])
df = pd.DataFrame(dict(
DEGREE_CENTRALITY = nx.degree_centrality(G),
EIGENVECTOR = nx.eigenvector_centrality(G),
KATZ = nx.katz_centrality_numpy(G),
CLOSENESS_CENTRALITY = nx.closeness_centrality(G),
BETWEENNESS_CENTRALITY = nx.betweenness_centrality(G),
CLUSTCOEF = nx.clustering(G),
))
df.index += 1
df.to_csv('test.csv')