首页 > 解决方案 > 为节点分配颜色时出现 KeyError

问题描述

尝试创建网络时出现 KeyError。

我的数据集是

Node    Neighbors       Colour  Weight
 Luke   Alte            orange    3
 Luke   John            orange    3
Michael Laura           red       43
Ludo    Stella          orange   21
Alte    Ludo            blue     24
Alte    Luke            blue     24

上表按节点显示链接:

执行以下操作:

NROWS = None
def get_graph_from_pandas(df):
    
    G = nx.DiGraph() # assuming the graph is directed since e.g node 1 has 
                     # 3 as neighbour but 3 doesnt have 1 as neighbour
    
    
    for row in df.itertuples(): # row is the row of the dataframe
        n = row.Node
        w = row.Weight
        c = row.Colour
        neighbors = row.Neighbors
        
        G.add_node(n, weight = w, colour = c)
        
        for neigh in neighbors:
            #add edge weights here, attribute of G.add_edge
            G.add_edge(n,neigh)  
            
    return G
        
        
        
G = get_graph_from_pandas(df)

print("Done.")
print("Total number of nodes: ", G.number_of_nodes())
print("Total number of edges: ", G.number_of_edges())

pos = nx.draw(G, with_labels=True, 
              node_color=[node[1]['colour'] for node in G.nodes(data=True)], 
              node_size=200)

给了我一个 KeyError: 'color'。

当我打印

for node in G.nodes(data=True):     
     try:         
        node[1]['colour']     
     except KeyError:         
        print(node)

我明白了

('A', {}) 
('l', {}) 
('t', {}) 
('e', {})

你能解释一下导致错误的原因吗?谢谢

更新:我认为错误来自这里

 for neigh in neighbors:
                #add edge weights here, attribute of G.add_edge
                G.add_edge(n,neigh)  

标签: pythonnetworkx

解决方案


二战的答案解决了一个问题。

但是有很多问题需要解决:

  1. 只有 Node 列中的节点才会有颜色,仅在 Neighbors 列中介绍的用户将在 中创建G.add_edge(n,neighbor),并且不会分配颜色。您需要决定为这些节点设置哪种颜色。

  2. 您要归因于边缘的权重正在归因于节点。

df = pd.DataFrame(  data = {"Node": ["Luke", "Luke", "Michael", "Ludo", "Alte", "Alte"],
                            "Neighbors": ["Ludo", "John", "Laura", "Stella", "Ludo", "Luke"],
                            "Colour": ["orange", "orange", "red", "orange", "blue", "blue"], 
                            "Weight": [3, 3 ,43, 21, 24, 24] 
                        }
              )
   

NROWS = None
def get_graph_from_pandas(df, v = False):
    
    G = nx.DiGraph() # assuming the graph is directed since e.g node 1 has 
                     # 3 as neighbour but 3 doesnt have 1 as neighbour
    
    for row in df.itertuples():
        print(row)
        n = row.Node
        w = row.Weight
        c = row.Colour
        neighbor = row.Neighbors
        
        G.add_node(n, weight = w, colour = c) # only nodes in column Node will have color
                                              # users that are only introduced in Neighbors column dwont have column
        if neighbor not in G.nodes:
            G.add_node(neighbor, weight = w, colour = "yellow") # this will set the default color to yellow
        G.add_edge(n,neighbor, weight = w) # weight of edge
            
    return G
        
G = get_graph_from_pandas(df, v = False)

print("Done.")
print("Total number of nodes: ", graph.number_of_nodes())
print("Total number of edges: ", graph.number_of_edges())

fig = plt.figure(figsize=(2,2))

pos = nx.draw(G, with_labels=True, 
              node_color=[node[1]['colour'] for node in G.nodes(data=True)], 
              node_size=200)

for node in G.nodes(data=True):
    try:
        node[1]['colour']
    except KeyError:
        print(node)


推荐阅读