【问题标题】:KeyError after re-running the (same) code重新运行(相同)代码后的 KeyError
【发布时间】:2022-01-19 01:18:10
【问题描述】:

当我尝试运行以下代码时返回 KeyError:

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]

我的数据框有以下列:

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

我知道关于 KeyError 名称有很多问题,但奇怪的是,在不更改任何内容的情况下,运行代码时会出现此错误,但之前我可以运行代码而没有错误。什么也没有变。 对此的任何帮助都会很棒!

追溯:

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'

【问题讨论】:

  • 1) 请发布回溯。 2) 这可能发生在像 Jupyter Notebook(或 IDE)这样的环境中,其中变量保留在范围内,否则它们会脱落,或者在调试时手动定义变量而不是手动删除时。然后,一旦内核重新启动,并且脚本“自然”运行,它就会暴露手动定义的变量。
  • 嗨 S3DEV,我将添加回溯。我已经重新启动了你的内核,但我得到了同样的错误

标签: python pandas networkx


【解决方案1】:

试试:

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

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

或者使用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']

【讨论】:

  • 感谢 Corralien,它解决了这个问题。但是,它与对节点 v 的访问有关。我需要保持这种格式,因为我必须按如下方式访问节点for v, w in G.edges: if G.nodes[v]["Label_Source"] == G.nodes[w]["Label_Source"]。这将返回相同的错误:/
  • 不可能:Label_SourceLabel_Target 不是节点属性,而是边缘属性。您无法通过节点访问它们(我认为:))
  • 仅供参考,如果您可能感兴趣并提供一些帮助,我已经为这个问题提供了赏金:stackoverflow.com/questions/67024111/…。由于它与这篇文章有关,也许你也想看看它
猜你喜欢
  • 1970-01-01
  • 2014-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多