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

如何将source-target-weight结构DataFrame导出为指定格式的JSON文件

实现代码

你可以直接用pandas内置方法完成转换,全程不需要手动循环拼接:

import pandas as pd
import json

# 替换为你自己的DataFrame变量名
df = ... 

# 生成符合要求的links列表
links = df[["source", "target", "weight"]].to_dict("records")

# 提取所有唯一节点生成nodes列表
all_nodes = pd.unique(df[["source", "target"]].values.ravel())
nodes = [{"id": node} for node in all_nodes]

# 拼接结构并导出为JSON文件
output_data = {"nodes": nodes, "links": links}
with open("graph.json", "w", encoding="utf-8") as f:
    json.dump(output_data, f, indent=2, ensure_ascii=False)

说明

  • 用to_dict("records")可以直接将DataFrame每行转为字典,输出的列表结构完全匹配links的要求,比手动循环效率高得多
  • 如果你需要nodes按固定顺序排列,可以将all_nodes那行修改为:
    all_nodes = sorted(pd.unique(df[["source", "target"]].values.ravel()))
    
  • 导出时加indent=2可以实现你示例中的缩进效果,ensure_ascii=False用于兼容节点名为中文的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:48:02