python - 从 numpy 数组创建图形顶点

标签 python arrays numpy networkx

我有一个充满值的 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 个节点。但是,当您具有相同的值时,这会变得更加棘手。例如:

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

现在,因为所有值都相同-(1),所以只有一个节点将被添加到图中。有办法绕过这个吗?

最佳答案

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

关于python - 从 numpy 数组创建图形顶点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30921360/

相关文章:

python - 正确使用 numpy 插值

python - 如何使用 * 或捕获字符串?用 python 正则表达式中的组

arrays - 使用 VB .net 从进程数组中删除重复项

c - 获取仅初始化第一项的数组的内存空间

python - pandas:将距离矩阵转换为字典,其中元素按接近度排序

python - python 中 numpy 数组的 len()

python - 如何从 dtype 为字符串的 tf.tensor 中获取字符串值

Ruby 循环数组并为每个数组对象创建哈希

python - numpy 将 int 解析为位分组

python - 用于查找行为奇怪的回文的正则表达式