簡體   English   中英

從有條件的圖中刪除節點

[英]remove nodes from a graph with a condition

我的代碼首先讀取包含具有屬性的節點和弧的圖形,然后計算節點attributes('criticité') 之后,它在條件下刪除節點。

這是我的代碼,我收到的類型錯誤是TypeError: unhashable type: 'dict'

#parsing
import matplotlib.pyplot as plt
import networkx as nx
G=nx.read_graphml("C:/Users/PlacisAdmin/Desktop/gephi/ex2.graphml",node_type=str)
nx.draw(G, with_labels=True)
plt.show()


# chnage nodes attributes
for u, v, weight in G.edges.data('weight'):
          if weight !=1:
             G.node[u]['criticité'] = float(G.node[u]['occurence']) * float (G.node[u]['détection']) * float (G.node[u]['gravité']) * weight
             G.node[v]['criticité'] = float(G.node[v]['occurence']) * float (G.node[v]['détection']) * float (G.node[v]['gravité']) * weight
print ("avant")
print (G.nodes.data('label'))
print (G.nodes.data('criticité'))


# calculate system crticité
for n in G.nodes():
    if G.node[n]['label']in ['1','2','3','4']:
        G.node[n]['criticité']=sum(G.node[t]['criticité'] for t in G.successors(n))

print ("après")
print (G.nodes.data('label'))
print (G.nodes.data('criticité'))

# eliminate nodes 
for d in G.nodes():
    if G.node[d]['label']in ['1','2','3','4'] and G.node[d]['criticité']> 30:
      G.remove_nodes_from(G.node[t]for t in G.successors(d) )

# show the graph
nx.draw(G, with_labels=True)
plt.show()

我相信你的錯誤在這一行:

G.remove_nodes_from(G.node[t]for t in G.successors(d) )

G.node[t]是一個包含節點t所有屬性的字典。 所以它正在尋找一個節點,它節點t屬性的字典。 但是,networkx 不允許節點成為字典。 因此,當它開始尋找要刪除的節點時,它會給您一條錯誤消息。

你幾乎肯定是想打電話

G.remove_nodes_from(t for t in G.successors(d))

可能與此重復: https : //stackoverflow.com/a/19371472/8933502

dict是可變的,因此不能被散列。 例如,您可以創建自己的可散列字典並將其散列在其id(d)上(不可變的東西)。

暫無
暫無

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

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