存储和访问节点属性python networkx [英] Storing and Accessing node attributes python networkx
问题描述
我有一个使用python networkx
创建的节点网络.我想在节点中存储信息,以便以后可以基于节点标签(节点名称)和存储信息的字段(例如节点属性)访问信息.存储的信息可以是字符串或数字,我希望这样做的方式是,如果xyz
是节点:
I have a network of nodes created using python networkx
. i want to store information in nodes such that i can access the information later based on the node label (the name of the node) and the field that in which the information has been stored (like node attributes). the information stored can be a string or a number I wish to do so in a manner such that if xyz
is a node:
然后我要保存两个或三个具有字符串的字段,例如xyz
dob=1185
的出生日期,xyz
pob=usa
的出生地点以及xyz
then I want to save two or three fields having strings like the date of birth of xyz
dob=1185
, the place of birth of xyz
pob=usa
, and the day of birth of xyz
dayob=monday
.
我知道我可以使用G.add_node
中的属性字典字段...但是我似乎无法为特定字段访问它.如果还有其他方法,我将不胜感激.
I know that i can use G.add_node
has the attribute dictionary field in it...but I can't seem to access it for a particular field. if there is any other way i would appreciate it.
i想将xyz
与网络中具有相同公共信息的其他节点进行比较.即节点xyz
与节点abc
的交点基于咬合日期,出生地点和出生日期
i then want to compare xyz
with other nodes in the networks having the same information in common. i.e. intersection of node xyz
with node abc
based on date of bith, place of birth and day of birth
例如,如果节点xyz
和abc
具有边缘,则分别打印它们的dob
,pob
和dayob
e.g for if nodes xyz
and abc
have an edge print their respective dob
s, their pob
s and their dayob
s
推荐答案
正如您所说,将节点添加到图形中只是添加属性的问题
As you say, it's just a matter of adding the attributes when adding the nodes to the graph
G.add_node('abc', dob=1185, pob='usa', dayob='monday')
或作为字典
G.add_node('abc', {'dob': 1185, 'pob': 'usa', 'dayob': 'monday'})
要访问属性,只需像使用任何词典一样访问它们
To access the attributes, just access them as you would with any dictionary
G.node['abc']['dob'] # 1185
G.node['abc']['pob'] # usa
G.node['abc']['dayob'] # monday
您说要查看已连接节点的属性.这是一个有关如何实现的小例子.
You say you want to look at attributes for connected nodes. Here's a small example on how that could be accomplished.
for n1, n2 in G.edges_iter():
print G.node[n1]['dob'], G.node[n2]['dob']
print G.node[n1]['pob'], G.node[n2]['pob']
# Etc.
从networkx 2.0开始,G.edges_iter()已替换为G.edges().这也适用于节点.我们将data=True
设置为访问属性.现在的代码是:
As of networkx 2.0, G.edges_iter() has been replaced with G.edges(). This also applies to nodes. We set data=True
to access attributes. The code is now:
for n1, n2 in list(G.edges(data=True)):
print G.node[n1]['dob'], G.node[n2]['dob']
print G.node[n1]['pob'], G.node[n2]['pob']
# Etc.
注意::在 networkx 2.4 中,G.node[]
已替换为G.nodes[]
.
这篇关于存储和访问节点属性python networkx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!