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

如何在Python中将DataFrame转换为可导入Triple Store的Turtle格式?

把Pandas DataFrame转换为Turtle格式并加载到Blazegraph

完全可以实现,你的DataFrame每一行正好对应一个标准RDF三元组(主语=mesh_code,谓语=skos_rel,宾语=MDR_code),转成Turtle格式后直接就能导入Blazegraph这类三元组存储。下面是两种可行的实现方式:

方法一:用rdflib(推荐,更规范)

rdflib是Python处理RDF的标准库,能自动处理命名空间、URI格式等细节,避免手动拼接出错。

  1. 先安装依赖:
pip install pandas rdflib
  1. 代码实现:
import pandas as pd
from rdflib import Graph, URIRef, Namespace

# 读取你的DataFrame(如果已经在内存里就直接用现有对象)
df = pd.read_csv("你的数据文件路径.csv")

# 初始化RDF图对象
g = Graph()

# 绑定SKOS命名空间,让生成的Turtle更简洁(可选但推荐)
SKOS = Namespace("http://www.w3.org/2004/02/skos/core#")
g.bind("skos", SKOS)

# 遍历DataFrame生成三元组
for _, row in df.iterrows():
    # 去除URI前后的<>,转成RDF标准的URIRef对象
    subject = URIRef(row['mesh_code'].strip('<>'))
    predicate = URIRef(row['skos_rel'].strip('<>'))
    obj = URIRef(row['MDR_code'].strip('<>'))
    g.add((subject, predicate, obj))

# 保存为Turtle格式文件
g.serialize(destination="mesh_meddra_mappings.ttl", format="turtle")

生成的Turtle文件会自动包含命名空间声明,格式更规范,示例片段:

@prefix skos: <http://www.w3.org/2004/02/skos/core#> .

<http://id.nlm.nih.gov/mesh/D000012> skos:exactMatch <https://identifiers.org/meddra:10083851> .
<http://id.nlm.nih.gov/mesh/D000026> skos:exactMatch <https://identifiers.org/meddra:10062935> .

方法二:手动拼接字符串(轻量快速)

如果不想引入rdflib依赖,可以直接用pandas拼接字符串生成Turtle:

import pandas as pd

df = pd.read_csv("你的数据文件路径.csv")

# 构建Turtle内容
turtle_content = []
# 添加命名空间声明(可选)
turtle_content.append("@prefix skos: <http://www.w3.org/2004/02/skos/core#> .")
# 遍历每行生成三元组语句
for _, row in df.iterrows():
    turtle_content.append(f"{row['mesh_code']} {row['skos_rel']} {row['MDR_code']} .")

# 写入文件
with open("mesh_meddra_mappings.ttl", "w", encoding="utf-8") as f:
    f.write("\n".join(turtle_content))

加载到Blazegraph的步骤

生成ttl文件后,有两种常见导入方式:

  • Web界面导入:打开Blazegraph控制台(默认地址http://localhost:9999/blazegraph),进入Update页面,选择File Upload,上传你的ttl文件,点击Update即可完成导入。
  • SPARQL命令导入:如果需要自动化,可以在控制台的Query页面执行:
LOAD <file:///path/to/your/mesh_meddra_mappings.ttl>

注意路径要根据系统调整(Windows下需改成类似file:///C:/path/to/file.ttl)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 09:07:10