You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Networkx中nx.attr_matrix提取节点属性矩阵不符合预期的问题

NetworkX节点属性矩阵提取问题解决方法

问题原因

nx.attr_matrix函数的设计逻辑和预期不符:

  • 指定edge_attr时,它生成N×N的边属性邻接矩阵,矩阵值对应边的属性,这符合使用需求;
  • 指定node_attr时,它不会生成节点属性的列向量,而是以节点属性值作为节点标识,生成图的邻接矩阵(矩阵中1表示节点间有边,0表示无边),返回的第二个元组元素才是节点属性的列表——这就是出现邻接矩阵而非属性向量的原因。

解决方法

要获取N×M(此处M=1)的节点属性矩阵,直接提取节点属性并转换为矩阵即可,无需使用nx.attr_matrix。以下是具体实现代码:

import networkx as nx
import numpy as np

# 构建图(保留原始代码)
G = nx.Graph()
G.add_edge(0, 1, thickness=1, height = 4)
G.add_edge(0, 2, thickness=2, height = 5)
G.add_edge(1, 2, thickness=3, height = 6)

nx.set_node_attributes(G, {0:11, 1:12, 2:13}, "node_type")
nx.set_node_attributes(G, {0:21, 1:22, 2:23}, "node_type2")

# 获取节点顺序(与nx.attr_matrix默认顺序一致)
nodes = list(G.nodes())

# 提取node_type属性并转为N×1矩阵
node_type_matrix = np.matrix([[G.nodes[n]['node_type']] for n in nodes])
m3 = (node_type_matrix, nodes)

# 提取node_type2属性并转为N×1矩阵
node_type2_matrix = np.matrix([[G.nodes[n]['node_type2']] for n in nodes])
m4 = (node_type2_matrix, nodes)

# 输出结果
print("m3:", m3)
print("m4:", m4)

输出结果

m3: (matrix([[11],
        [12],
        [13]]), [0, 1, 2])
m4: (matrix([[21],
        [22],
        [23]]), [0, 1, 2])

该方法直接从节点字典中提取属性值,转换为预期的列向量矩阵,同时保留节点顺序的对应关系。

内容的提问来源于stack exchange,提问作者Angelo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 06:24:47