Home > Enterprise >  KeyError after re-running the (same) code
KeyError after re-running the (same) code

Time:12-16

A KeyError is returned when I try to run the below code:

import pandas as pd
import networkx as nx
from matplotlib import pyplot as plt

G = nx.from_pandas_edgelist(df, 'Source', 'Target',  edge_attr=True)
df_pos = nx.spring_layout(G,k = 0.3) 

nx.draw_networkx(G, df_pos)
plt.show()

node_color = [
    '#1f78b4' if G.nodes[v]["Label_Source"] == 0 # This returns the error
    else '#33a02c' for v in G]

My dataframe has the following columns:

Source  Target      Label_Source Label_Target
string1  string2          1           0
string1  string4          1           1
string4  string5          1           0

I know that there are many questions on the KeyError name, but what was weird is that without changing anything this error appeared while running the code, but previously I could run the code with no errors. Nothing has changed. Any help on this would be great!

Traceback:

KeyError                                  Traceback (most recent call last)
<ipython-input-9-1266cd6e1844> in <module>
----> 1 node_color = [
      2     '#1f78b4' if G[v]["Label_Source"] == 0
      3     else '#33a02c' for v in G]

<ipython-input-9-1266cd6e1844> in <listcomp>(.0)
      1 node_color = [
----> 2     '#1f78b4' if G[v]["Label_Source"] == 0
      3     else '#33a02c' for v in G]

~/opt/anaconda3/lib/python3.8/site-packages/networkx/classes/coreviews.py in __getitem__(self, key)
     49 
     50     def __getitem__(self, key):
---> 51         return self._atlas[key]
     52 
     53     def copy(self):

KeyError: 'Label_Source'

CodePudding user response:

Try:

node_color = np.where(df['Label_Source'] == 0, '#1f78b4', '#33a02c').tolist()
print(node_color)

# Output:
['#33a02c', '#33a02c', '#33a02c']

Or using networkx:

node_color = ['#1f78b4' if v == 0 else '#33a02c'
                  for v in nx.get_edge_attributes(G, 'Label_Source')]
print(node_color)

# Output:
['#33a02c', '#33a02c', '#33a02c']
  • Related