【发布时间】:2021-01-26 18:56:21
【问题描述】:
我正在使用 Python 和 networkx 包从文件中读取边缘列表以构建图形。
我的边缘列表看起来像这样:
[(0, 114, {'pts': array([[ 1, 822],
[ 1, 821],
[ 2, 820],
[ 3, 819]], dtype=int16), 'weight': 23.38477631085024}),
(1, 110, {'pts': array([[ 1, 3],
[ 1, 2],
[ 2, 1]], dtype=int16), 'weight': 18.414213562373096})]
我写了这个边缘列表:
nx.write_edgelist(G, 'my_el.edgelist', data=True)
我的边由开始和结束节点定义,然后,我有我的权重。每条边有两个权重。第一个权重是像素坐标数组,第二个是浮点数。
该图是使用 build_sknw function 从带有“sknw”库的骨架构建的:
def build_sknw(ske, multi=False):
buf = buffer(ske)
nbs = neighbors(buf.shape)
acc = np.cumprod((1,)+buf.shape[::-1][:-1])[::-1]
mark(buf, nbs)
pts = np.array(np.where(buf.ravel()==2))[0]
nodes, edges = parse_struc(buf, pts, nbs, acc)
return build_graph(nodes, edges, multi)
现在我想阅读这个边缘列表来构建一个图表。但是,Python 不会将我的像素坐标数组识别为单个权重元素。
我试过nx.read_edgelist('my_el.edgelist', data=True),它给了我以下错误:
TypeError: Failed to convert edge data (["{'pts':", 'array([[', '1,', '822],']) to dictionary.
nx.read_edgelist('my_el.edgelist', data=['pts', 'weight'] 给我:
IndexError: Edge data ["{'pts':", 'array([[', '1,', '822],'] and data_keys ['pts', 'weight'] are not the same length
nx.read_edgelist('my_el.edgelist', data=(('pts', int), ('weight', float'))) 给了我
IndexError: Edge data ["{'pts':", 'array([[', '1,', '822],'] and data_keys (('pts', <class 'int'>), ('weight', <class 'float'>)) are not the same length
我假设该函数在将数组作为权重或 my_el.edgelist 文件的格式方面存在问题,但我真的不知道如何通过转换为正确解决此问题而无需任何解决方法字符串,或类似的。
如果有人能指出正确的方向并帮助我解决这个问题,我将不胜感激!
【问题讨论】:
-
您能否分享一个最小的示例,如何创建边缘列表?您是否也可以更改边缘列表的创建?因为
pts中的额外换行符可能是您的问题的一部分。 -
您的 edgelist 格式很复杂,这会导致 parse_edgelist 函数失效。我建议使用纯 Python 阅读 edgelist 文件。自己逐行解析并使用权重为每条边创建数据。然后您可以使用 read_edgelist 创建图形,或者您可以使用
add_edge使用所有属性逐边创建它 -
@Sparky05,是的,我通常可以更改创建边缘列表的方式。但是,创建边缘的方式是使用另一个包中的内置 sknw 函数,我宁愿避免重写导入的函数。但是指出额外的换行符是有帮助的,谢谢!
-
感谢@RamNarasimhan,使用普通的 python 数组,而不是 numpy 数组,创造了奇迹!
标签: python arrays types networkx