由网络中错误的属性分配导致的KeyError?

2022-03-31 00:00:00 python pandas networkx

问题描述

我有一个格式不正确的数据集,因为它包含以下列

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

如果你能帮助我了解如何修复这个问题并复制代码,那就太好了。我想错误还在于试图循环访问字符串而不是索引。


解决方案

创建图表后:

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

您具有以下属性:

# For edges:
print(G.edges(data=True))
[('E', 'N', {'Label_Source': 0.0, 'Label_Target': 0.0}),
 ('N', 'A', {'Label_Source': 1.0, 'Label_Target': 0.0}),  # Problem here
 ('A', 'B', {'Label_Source': 1.0, 'Label_Target': 1.0}),
 ('A', 'C', {'Label_Source': 1.0, 'Label_Target': 0.0}),
 ('A', 'D', {'Label_Source': 1.0, 'Label_Target': 0.0}),
 ('C', 'S', {'Label_Source': 0.0, 'Label_Target': 0.0}),
 ('S', 'G', {'Label_Source': 0.0, 'Label_Target': 0.0}),
 ('S', 'L', {'Label_Source': 0.0, 'Label_Target': 1.0})]

# For nodes:
print(G.nodes(data=True))
[('E', {}), ('N', {}), ('A', {}), ('B', {}),
 ('C', {}), ('D', {}), ('S', {}), ('G', {}), ('L', {})]

如您所见,节点没有属性。您必须将Label_xxx值从边缘属性复制到右侧节点:

# Don't use it, check update below
for source, target, attribs in G.edges(data=True):
    G.nodes[source]['Label'] = int(attribs['Label_Source'])
    G.nodes[target]['Label'] = int(attribs['Label_Target'])

print(G.nodes(data=True))
[('E', {'Label': 0}), ('N', {'Label': 1}), ('A', {'Label': 1}),
 ('B', {'Label': 1}), ('C', {'Label': 0}), ('D', {'Label': 0}),
 ('S', {'Label': 0}), ('G', {'Label': 0}), ('L', {'Label': 1})]

现在您可以为图形的每个节点设置颜色:

node_color = ['#1f78b4' if v == 0 else '#33a02c'
              for v in nx.get_node_attributes(G, 'Label').values()]

print(node_color)
['#1f78b4', '#33a02c', '#33a02c', '#33a02c',
 '#1f78b4', '#1f78b4', '#1f78b4', '#1f78b4', '#33a02c']

最后一步:

nx.draw_networkx(G, df_pos, label=True, node_color=node_color)
plt.show()

更新

我认为将颜色分配给节点的代码有问题。某些节点的颜色错误(例如,它们应该是绿色的,而它们是蓝色的)。

问题在于边('A', 'N') -> (1, 0),它被存储为('N', 'A') -> (1, 0),因为您的图不是有向的,所以边是('A', 'N')还是('N', 'A')并不重要。如果对您的问题有意义,您可以使用create_using=nx.DiGraph选项创建图表来解决此问题。

另一种解决方案是不从边属性创建Label属性,而是像我的previous answer建议的那样从数据帧创建属性:

for _, sr in df.iterrows():
    G.nodes[sr['Source']]['Label'] = int(sr['Label_Source'])
    G.nodes[sr['Target']]['Label'] = int(sr['Label_Target'])

print(G.nodes(data=True))
[('E', {'Label': 0}), ('N', {'Label': 0}), ('A', {'Label': 1}),
 ('B', {'Label': 1}), ('C', {'Label': 0}), ('D', {'Label': 0}),
 ('S', {'Label': 0}), ('G', {'Label': 0}), ('L', {'Label': 1})]

现在,您拥有每个节点的正确Label属性:

相关文章