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

如何使用Julia的DataFrames构造incidence matrix(关联矩阵)

Julia构造有向图关联矩阵实现方法

你可以直接用以下代码完成转换,逻辑清晰无需依赖额外的图包:

1. 基础稠密矩阵实现(适合小规模节点/边)

using DataFrames

# 构造你提供的测试DataFrame
df = DataFrame(Lines = 1:20, From = rand(1:10,20), To = rand(1:10,20))

# 计算节点总数、边总数
node_count = maximum([df.From; df.To])
edge_count = nrow(df)

# 初始化全0的关联矩阵,维度为「节点数 × 边数」
incidence_matrix = zeros(Int, node_count, edge_count)

# 遍历每条边赋值:起点位置设为1,终点位置设为-1
for (edge_idx, edge_info) in enumerate(eachrow(df))
    incidence_matrix[edge_info.From, edge_idx] = 1
    incidence_matrix[edge_info.To, edge_idx] = -1
end

2. 高效稀疏矩阵实现(适合大规模节点/边,内存占用更低)

using DataFrames, SparseArrays

df = DataFrame(Lines = 1:20, From = rand(1:10,20), To = rand(1:10,20))
node_count = maximum([df.From; df.To])
edge_count = nrow(df)

# 直接构造稀疏关联矩阵
I = vcat(df.From, df.To)
J = vcat(1:edge_count, 1:edge_count)
V = vcat(ones(Int, edge_count), -ones(Int, edge_count))
incidence_matrix_sparse = sparse(I, J, V, node_count, edge_count)

# 如需转为稠密矩阵,执行 `Matrix(incidence_matrix_sparse)` 即可

得到的矩阵中,每一列对应你Lines列的一条边,行对应节点编号:

  • 值为1:对应行的节点是当前列边的起点
  • 值为*-1*:对应行的节点是当前列边的终点
  • 值为0:对应节点和当前边无关联

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:18:04