python - 为节点分配颜色时出现 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
上表按节点显示链接:
- 节点 Luke 与 Alte 和 John 相关联。它的边重为 3,颜色为橙色
- 节点 Michael 与 Laura 相关联。它的重量为 43,颜色为红色
- 节点 Ludo 与 Stella 链接。它的重量为 21,颜色为橙色
- 节点 Alte 与 Luke 和 Ludo 链接。它有蓝色和重量 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)
解决方案
二战的答案解决了一个问题。
但是有很多问题需要解决:
只有 Node 列中的节点才会有颜色,仅在 Neighbors 列中介绍的用户将在 中创建
G.add_edge(n,neighbor)
,并且不会分配颜色。您需要决定为这些节点设置哪种颜色。您要归因于边缘的权重正在归因于节点。
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)
推荐阅读
- python - ValueError:使用序列设置数组元素。在 session.run
- wordpress - 更改网址后无法打开 WordPress 网站
- html - 删除 Chrome 中的输入历史记录
- javascript - HERE 地图 API 是否有放大/缩小事件?
- css - 如何缩放 SVG 以适应其中的动态内容
- java - 调整按钮上的背景图像大小
- typescript - 使用条件映射键时正确解析对象项类型(键应用于对象)
- c# - 默认标识页面显示在 Azure 发布的站点上
- javascript - 使用 async/await 错误处理避免 try-catch 块
- http - 解密后的反向代理服务文件