简体   繁体   English

在networkx中从节点名称到其索引的映射,反之亦然

[英]Mapping from a node's name to its index and vice versa in networkx

Given a networkx graph, is there a way to map from a node's name to its index in the adjacency matrix and vice versa?给定一个networkx图,有没有办法将节点的名称映射到邻接矩阵中的索引,反之亦然?

I know that G.nodes() returns a list where the index of the node in the list corresponds to its index in the adjacency matrix.我知道G.nodes()返回一个列表,其中列表中节点的索引对应于它在邻接矩阵中的索引。

So to map from a node's name to a node's index, I'm doing a very stupid way of storing the node's index in a dictionary and map it by the node's name.因此,为了从节点名称映射到节点索引,我采用了一种非常愚蠢的方法将节点的索引存储在字典中并按节点名称进行映射。

To map from a node index to its name, then I create another dictionary similar to the one before (with the keys and values switched).为了从节点索引映射到它的名称,我创建了另一个类似于之前的字典(键和值切换)。

Is there a better way to do this?有一个更好的方法吗?

Short answer: not as far as I know.简短的回答:据我所知没有。 I have a bunch of code similar to yours, though with a few improvements.我有一堆类似于你的代码,但有一些改进。

The first thing you can do is remember that each node has a dictionary hanging on it.您可以做的第一件事是记住每个节点上都挂着一本字典。 G.node[node_name] is a dictionary of whatever you want. G.node[node_name]是你想要的任何字典。 You can thus do something like:因此,您可以执行以下操作:

G.node[node_name]['index'] = G.nodes().index(node_name)

Which at least hangs the information on the graph, but in the same fragile way as your method: if you modify your graph the behaviour of G.nodes() isn't documented.这至少将信息挂在图形上,但与您的方法一样脆弱:如果您修改图形,则不会记录 G.nodes() 的行为。

A probably-better solution is to use the nodelist kwarg for G.adjacency_matrix .一个可能更好的解决方案是将nodelist kwarg 用于G.adjacency_matrix This takes a list of node names and outputs the adjacency matrix in that order.这需要一个节点名称列表并按该顺序输出邻接矩阵。 You can thus set up the list in a sensible-for-your-application way, rather than the pseudorandom behaviour of G.nodes().因此,您可以以适合您的应用程序的方式设置列表,而不是 G.nodes() 的伪随机行为。 For instance, you can pass it a sorted list of your nodes ( sorted(G.nodes()) ) if the nodes are named in a useful way.例如,如果节点以有用的方式命名,您可以将节点的排序列表( sorted(G.nodes()) )传递给它。

For small / moderate graphs, one simple option is to store the node names as a list:对于小/中等图形,一个简单的选择是将节点名称存储为列表:

nodes_list = np.array(list(g.nodes()))

To recover the name from the index, eg:要从索引中恢复名称,例如:

node_name = nodes_list[4]

To recover the index from the name:要从名称恢复索引:

node_id = np.where(nodes_list == "n4")[0][0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM