I have a directed graph-tool graph g
. I also have already calculated the pagerank for each vertex in the graph using graph_tool.centrality.pagerank
as shown below.
v_pr = g.new_vertex_property('float')
pr = pagerank(u, prop=v_pr)
u.vp['vertex_pagerank'] = v_pr
From here, I can access the pagerank value of a vertex given its index.
What I want to do, however, is to extract, say, the top 10 vertices of the graph in terms of their pagerank values.
Is there a quick way to do this on graph-tool
?
Assuming g
is our graph and that we we have already computed our PageRank values and stored them in u.vp['vertex_pagerank']
, we can convert the vertex property to a list of (vertex_index
, pagerank_value
) tuples
vertex_pagerank_list = [(v, u.vp['vertex_pagerank'][v]) for v in u.vertices()]
We can then sort the list based on pagerank_value
in descending order
vertex_pagerank_list.sort(key=lambda x: x[1], reverse=True)
To extract the top 10 vertices:
top_10_vertices = vertex_pagerank_list[:10]
# Print the top 10 vertices and their PageRank values
for vertex, pr_value in top_10_vertices:
print(f"Vertex: {int(vertex)}, PageRank: {pr_value}")