从numpy数组创建图顶点

2024-09-27 23:24:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个numpy数组,我想为数组中的每个点创建顶点。我使用networkx作为图形支持方法(文档如下: http://networkx.github.io/documentation/latest/tutorial/

我想把数组中的每个元素当作一个像素位置,并在每个位置创建一个顶点实例。这很容易使用一个简单的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

如预期,将打印15个节点。但是,当您有相同的值时,这会变得更加棘手。例如:

^{pr2}$

现在,由于所有值都相同-(1),因此只有一个节点将添加到图形中。有没有办法绕过这个问题?在


Tags: 方法文档ionumpynetworkxgithubhttp图形
1条回答
网友
1楼 · 发布于 2024-09-27 23:24:44

NetworkX要求每个节点都有一个唯一的名称。您可以生成唯一的名称,然后将数组的元素设置为节点的属性,例如

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

相关问题 更多 >

    热门问题