【发布时间】:2021-04-09 15:36:01
【问题描述】:
我的数据集格式不正确,因为它有以下列
Source Target Label_Source Label_Target
E N 0.0 0.0
A B 1.0 1.0
A C 1.0 0.0
A D 1.0 0.0
A N 1.0 0.0
S G 0.0 0.0
S L 0.0 1.0
S C 0.0 0.0
Label_Source 和 Label_Target 是节点属性 Label_Source 是源的属性,而 Label_Target 是目标的属性。 尝试复制以下项目:https://www.fatalerrors.org/a/python-networkx-learning-notes.html,我遇到了一些错误,包括由于 Label_Source 导致的 KeyError。正如这个答案中所解释的:KeyError after re-running the (same) code,问题似乎是由边缘/节点属性中的错误分配引起的,因为代码正在读取 Label_Source 作为边缘的属性。 正如我所说,我想复制该项目,因此任何可以使其成为可能的格式都是可以接受的。但是,我真的很感激有人可以解释(不仅仅是展示)如何解决这个问题,因为我不清楚是什么驱动了它。 到目前为止我所做的如下所示:
import networkx as nx
from matplotlib import pyplot as plt
import pandas as pd
G = nx.from_pandas_edgelist(filtered, '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 # actually this assignment should just Label and it should include also Target, so the whole list of nodes and their labels. A way to address this would be to select all distinct nodes in the network and their labels
else '#33a02c' for v in G]
# Iterate through all edges
for v, w in G.edges:
if G.nodes[v]["Label_Source"] == G.nodes[w]["Label_Source"]: # this should refer to all the Labels
G.edges[v, w]["internal"] = True
else:
G.edges[v, w]["internal"] = False
如果您能帮助我了解如何解决问题并复制代码,那就太好了。我猜这个错误也在于尝试遍历字符串而不是索引。
【问题讨论】: