EFL
EFL

Reputation: 1008

Sort pagerank values of graph-tool vertices

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?

Upvotes: 1

Views: 593

Answers (2)

EFL
EFL

Reputation: 1008

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}")

Upvotes: 0

Rodrigo Vargas
Rodrigo Vargas

Reputation: 145

I'm new to graph-tool and was wondering about a similar problem. Don't know how efficient my solution is, but for what it's worth I ended up doing it like this:

vertices_by_rank = sorted(u.vertices(), key=lambda v: pr[v], reverse=True)

Upvotes: 0

Related Questions