2

I have a df from which I need to create a Knowledge Graph using RDFlib library in Python. So that I can visualize the created knowledge graph in various visualization tools like Protege, Webowl etc. How can this be done?enter image description here

Arya Stark
  • 205
  • 1
  • 11

1 Answers1

3

Here is my approach based on this answer. See also this notebook for outputs.


import pandas as pd
from rdflib import Graph, URIRef, Namespace

d = {
    "source": pd.Series(["Edwin", "Reema", "Ron", "Tomorrow"]),
    "target": pd.Series(["football", "karate", "singer", "holiday"]),
    "edge": pd.Series(["plays", "plays", "is", "is"]),
}

df = pd.DataFrame(d)

g = Graph()
n = Namespace('http://example.org/foo/')

for inded, row in df.iterrows():
    # add triple to rdf-graph
    g.add((URIRef(n+row["source"]), URIRef(n+row["edge"]), URIRef(n+row["target"])))

print(g.serialize(format='turtle'))

With some additional visualization code (based on https://stackoverflow.com/a/61483971/333403) you arrive at: visualization of rdf graph

cknoll
  • 2,130
  • 4
  • 18
  • 34