我使用 igraph 计算了每个节点的最佳网络数量,这是我使用的代码。
import igraph
g = igraph.Graph.Read_Ncol('data.txt')
dendrogram = g.community_edge_betweenness()
clusters = dendrogram.as_clustering()
membership = clusters.membership
现在我想使用 networkX 中的 set_node_attributes
函数来标记每个节点的社区数量。因此,如果我运行 nx.get_node_attributes(g,'counts')
它应该产生
{123: 2,
124: 3,
125: 4 and so on} where "123" is a node and "2" is the count associated
我想在这里使用 for 循环,但不知道如何开始。
编辑:
membership
#output:
[2,
3,
4]
最佳答案
我假设membership
是一个以节点为键、计数为值的字典,然后根据您使用的networkx版本(我使用的是v2.1),检查 set_node_attributes
的语法,对于 version 2. 1、是set_node_attributes(G, values, name=None)
,
所以你只需这样做
nx.set_node_attributes(G, membership, 'counts')
print G[123]['count']
#output 2
然后使用 get_node_attributes
要提取相同的字典,like this
attribute_dict = nx.get_node_attributes(G, 'counts')
print attribute_dict[123]
#output : 2
更新:假设 membership
是一个计数列表,那么它将与 G.nodes()
的顺序相同,所以我们可以
node_list = list(G.nodes())
count_dict = { k:v for k,v in zip(node_list,membership)}
然后做
nx.set_node_attributes(G, count_dict, 'counts')
关于python - 使用networkX向节点添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51052465/