重新标记networkx中图的节点 [英] Relabeling Nodes of a graph in networkx

查看:776
本文介绍了重新标记networkx中图的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试处理Wiki-Vote.txt( https: //snap.stanford.edu/data/wiki-Vote.html ).有7115个ID范围从3到8297的节点.我想重新标记从0到7114的节点.我检查了relabel_nodes()中的映射,但仍然无法解决问题.请提出建议.谢谢

I am trying to process the graph given in wiki-Vote.txt (https://snap.stanford.edu/data/wiki-Vote.html). There are 7115 nodes with id ranging from 3 to 8297. I want to relabel the nodes from 0 to 7114. I checked the mappings in relabel_nodes() but still could not solve the problem. Please suggest. thanks

推荐答案

编辑 我不确定是否是新的,但我的原始答案没有提及 nx.convert_node_labels_to_integers(G, first_label=0, ordering='default', label_attribute=None).因此,对于给定的图形G,您可以 H=nx.convert_node_labels_to_integers(G).这不能保证顺序与G中的顺序相同.如果调用H=nx.convert_node_labels_to_integers(G, label_attribute='original_name'),则可以将原始标签存储在H中.您可以通过设置ordering=sorted(G.nodes())来保证顺序与G中的顺序相同.

edit I'm not sure if it's new, but my original answer didn't mention nx.convert_node_labels_to_integers(G, first_label=0, ordering='default', label_attribute=None). So for a given graph G, you can do H=nx.convert_node_labels_to_integers(G). This doesn't guarantee that the order is the same as in G. You can have the original label be stored in H if you call H=nx.convert_node_labels_to_integers(G, label_attribute='original_name'). You can guarantee that the order is the same as in G, by setting ordering=sorted(G.nodes()).

原始答案

给出具有一组节点的图G,最简单的事情就是

Given a graph G with some set of nodes, the simplest thing would be

mapping = {old_label:new_label for new_label, old_label in enumerate(G.nodes())}
H = nx.relabel_nodes(G, mapping)

这将创建一个字典mapping,其键是旧标签,值是它们的新标签(请阅读词典理解).新标签的顺序由G.nodes()返回值的顺序给出(您无法控制).新图H的节点标签已更改.

This will create a dictionary mapping whose keys are the old labels and whose values are their new labels (read up on dictionary comprehensions). The ordering of the new labels is given by the order that G.nodes() returns the values (which you can't control). The new graph H has the node labels changed.

如果要特定顺序,则需要适当地对G.nodes()进行排序.因此,您可以

If you want a specific order, you need to sort G.nodes() appropriately. So you can do

nodelist = G.nodes()
nodelist.sort()
mapping = {old_label:new_label for new_label, old_label in enumerate(nodelist)}
H = nx.relabel_nodes(G, mapping)

,将按数字顺序(如果节点名称为字符串,则按字母顺序)排序.如果需要其他自定义顺序,则必须弄清楚如何对节点列表进行排序.

which would have them sorted in numerical order (or alphabetical order if the node names are strings). If you want some other custom order, you'll have to figure out how to sort nodelist.

这篇关于重新标记networkx中图的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆