KeyError after re-running the (same) code(重新运行(相同)代码后出现KeyError)
本文介绍了重新运行(相同)代码后出现KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试运行以下代码时返回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'
推荐答案
尝试:
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']
这篇关于重新运行(相同)代码后出现KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:重新运行(相同)代码后出现KeyError


猜你喜欢
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 沿轴计算直方图 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12