简体   繁体   English

从numpy数组创建图顶点

[英]Creating graph vertices from numpy array

I have a numpy array full of values that I would like to create vertices from for every point in the array. 我有一个充满值的numpy数组,我想为数组中的每个点创建顶点。 I am using networkx as my graphing support method(documentation here: http://networkx.github.io/documentation/latest/tutorial/ ) 我使用networkx作为我的图形支持方法(此处的文档: http ://networkx.github.io/documentation/latest/tutorial/)

I would like to treat each element within the array as a pixel location and create a vertex instance at each location. 我想将数组中的每个元素视为像素位置,并在每个位置创建一个顶点实例。 This is easy using a simple for loop: 使用简单的for循环很容易:

new=np.arange(16)
gnew=nx.Graph()
for x in new:
    if new[x]>0:
        gnew.add_node(x)
h=gnew.number_of_nodes()
print h

And as expected, 15 nodes will be printed. 正如预期的那样,将打印15个节点。 However, this becomes more tricky when you have identical values. 但是,当您具有相同的值时,这会变得更加棘手。 For example: 例如:

new=np.ones(16)
gnew=nx.Graph()
for x in new:
    if new[x]>0:
        gnew.add_node(x)
h=gnew.number_of_nodes()
print h

Now, because all values are identical-(1), only one node will be added to the graph. 现在,因为所有值都相同 - (1),所以只有一个节点将添加到图中。 Is there a way to circumnavigate this? 有没有办法环游这个?

NetworkX requires that each node have a unique name. NetworkX要求每个节点都具有唯一的名称。 You could generate unique names and then set the elements of your array to be attributes of the nodes, eg 您可以生成唯一的名称,然后将数组的元素设置为节点的属性 ,例如

new = np.ones(16);
othernew = np.arange(16)

G = nx.Graph()
for i in range(len(othernew)):
   if new[i]>0:
      G.add_node(othernew[i])
      G.node[othernew[i]]['pos'] = new[i] #This gives the node a position attribute with value new[i]

h = G.order()
print(h)

>>16

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM