【问题标题】:Networkx create graph from adjacency matrix without edge weightsNetworkx 从没有边权重的邻接矩阵创建图
【发布时间】:2022-07-10 21:15:22
【问题描述】:

当我调用G = nx.convert_matrix.from_numpy_array(A, create_using=nx.DiGraph)(其中A 是一个0-1 邻接矩阵)时,生成的图会自动包含每条边的1.0 边权重。如何防止添加此属性?

我知道我会写

for _,_,d in G.edges(data=True):
    d.clear()

但我更喜欢一开始就没有添加属性。

【问题讨论】:

    标签: networkx


    【解决方案1】:

    使用本机 networkx 函数无法做到这一点。你可以这样做:

    G = nx.empty_graph(0, nx.DiGraph)
    G.add_nodes_from(range(A.shape[0]))
    G.add_edges_from(((int(e[0]), int(e[1])) for e in zip(*A.nonzero())))
    

    这正是nx.convert_matrix.from_numpy_array 函数在内部实现的方式。然而,我摆脱了所有控制,所以要小心这一点。更多详细信息可以找到here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多