Skip to content Skip to sidebar Skip to footer

Keyerror When Assign Colours To Nodes

I am getting a KeyError when I try to create a network. My dataset is Node Neighbors Colour Weight Luke Alte orange 3 Luke John orange 3

Solution 1:

wwii answer solves one problem.

However there are a number of problems that need to be fixed:

  1. Only nodes in column Node will have color, users that are only introduced in Neighbors column will be created in G.add_edge(n,neighbor), and won't have a color assigned. You need to decide which color to set for these nodes.

  2. The weight you want to attribute to the edges is being attributed to the nodes.

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 = Nonedefget_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 neighbourfor 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 columnif neighbor notin 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 edgereturn 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)

Solution 2:

Each item in df.Neighbors is a string. When you iterate over it with for neigh in neighbors: You add each character of the neighbor to the node. For example the first node looks like

>>>G.nodes>>>NodeView(('Luke', 'A', 'l', 't', 'e'))

As long as each row only has a single Neighbor, replace the for loop with

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

Although this doesn't alleviate the KeyError.

While 'John', 'Laura', and 'Stella' are neighbors they are also nodes in the graph but they were created with .add_edge and never had a color assigned to them.

>>> for thing in G.nodes.items():
... print(thing)
('Luke', {'weight': 3, 'colour': 'orange'})
('Alte', {'weight': 24, 'colour': 'blue'})
('John', {})
('Michael', {'weight': 43, 'colour': 'red'})
('Laura', {})
('Ludo', {'weight': 21, 'colour': 'orange'})
('Stella', {})

You can add those nodes first with default attributes before iterating:

...
    G.add_nodes_from(df.Neighbors,colour='white',weight=0)
    forrowin df.itertuples(): # rowis the rowof the dataframe
        ...

If your node attributes can begin with capitals the graph construction could be written:

defget_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
    
    
    G.add_nodes_from(df.Neighbors,Colour='white',Weight=0)
    G.add_edges_from(df[['Node','Neighbors']].itertuples(index=False))
    dg = df.set_index('Node')
    G.add_nodes_from(dg[['Colour','Weight']].T.to_dict().items())
        
    return G

>>> for thing in G.nodes(data=True):
... print(thing)
('Alte', {'Colour': 'blue', 'Weight': 24})
('John', {'Colour': 'white', 'Weight': 0})
('Laura', {'Colour': 'white', 'Weight': 0})
('Stella', {'Colour': 'white', 'Weight': 0})
('Ludo', {'Colour': 'orange', 'Weight': 21})
('Luke', {'Colour': 'orange', 'Weight': 3})
('Michael', {'Colour': 'red', 'Weight': 43})
>>> for thing in G.edges(data=True):
... print(thing)
('Alte', 'Ludo', {})
('Alte', 'Luke', {})
('Ludo', 'Stella', {})
('Luke', 'Alte', {})
('Luke', 'John', {})
('Michael', 'Laura', {})

You can get the node colors directly from G.nodes.items

pos = nx.draw(G, with_labels=True, 
              node_color=[d['Colour'] for n,d in G.nodes.items()], 
              node_size=200)

or nx.get_node_attributes

pos = nx.draw(G, with_labels=True, 
              node_color=nx.get_node_attributes(G,'Colour').values(),
              node_size=200)

Post a Comment for "Keyerror When Assign Colours To Nodes"