Search code examples
pythondataframesparqldbpedia

How to convert an element of dataframe to a varibale in Python


I have a dataframe and I want to use one of its elements in my sparql query but it is not working with the following code. In deed, the value of pp is equal to ['http://dbpedia.org/resource/Eurobike'] while I need to have it in this way http://dbpedia.org/resource/Eurobike. How can I convert this element of dataframe to a variable?

#testdf is a dataframe
pp=testdf.iloc[0:1, 100:101].values[0]

sparql = SPARQLWrapper("http://dbpedia.org/sparql")
sparql.setQuery("""
    SELECT ?p ?o
    WHERE {  <""" + str(pp) + """> ?p ?o . 
    filter langMatches(lang(?o),"en")
    }
""")
sparql.setReturnFormat(XML)
results = sparql.query().convert()
print(results.toxml())

Solution

  • You can convert DataFrame to list and then modify list into string to use it in your query

    pp=testdf.iloc[0:1, 100:101]
    var_pp=pp.values.tolist()
    

    and now you can use var_pp[0] in your query if it is string. check this thread and this article for more info.