簡體   English   中英

從numpy數組創建圖頂點

[英]Creating graph vertices from numpy array

我有一個充滿值的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM