如何使用Python从NetworkX中的特定节点属性获取值 [英] How to get values from specific node attributes in NetworkX with Python

查看:965
本文介绍了如何使用Python从NetworkX中的特定节点属性获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个小组项目上,我们需要从我们正在处理的图形中的特定节点属性创建所有值的列表.每个节点都有6个属性,我们只需要其中一个属性的所有值的列表即可.

I'm working on a group project and we need to create a list of all the values from a specific node attribute in the graph we are working on. Each node has 6 attributes, we just need a list of all the values for one of our attributes.

import networkx as nx
import scipy as sp
import matplotlib.pyplot as plt
%matplotlib inline 
import urllib

url = "http://josquin.cti.depaul.edu/~rburke/courses/s14/fmh.graphml"
sock = urllib.urlopen(url)  # open URL
fmh = nx.read_graphml(sock)

for i in fmh:
    if fmh.node[i]['Race'] == 'Asian':
        fmh.add_node(i, RaceN=0)
    elif fmh.node[i]['Race'] == 'Black':
        fmh.add_node(i, RaceN=1)
    elif fmh.node[i]['Race'] == 'Hisp':
        fmh.add_node(i, RaceN=2)
    elif fmh.node[i]['Race'] == 'NatAm':
        fmh.add_node(i, RaceN=3)
    elif fmh.node[i]['Race'] == 'Other':
        fmh.add_node(i, RaceN=4)
    elif fmh.node[i]['Race'] == 'White':
        fmh.add_node(i, RaceN=5)

for i in fmh:
    if fmh.node[i]['Sex'] == 'F':
        fmh.add_node(i, SexN=0)
    elif fmh.node[i]['Sex'] == 'M':
        fmh.add_node(i, SexN=1)

我认为这就是所有相关的内容.预加载的数据有5个属性,我们添加了6个属性,我们只是希望能够获取特定属性的值,例如说说RaceN属性的所有值的列表.

I think that's everything pertinent. The pre loaded data has 5 attributes, we added a 6th, we just want to be able to grab the values for a specific attribute, like say make a list of all the values for the RaceN attribute.

我们的想法是,我们有一个整数列表,可以在上面调用sp.bincount()函数.

The idea is that we have a list of integers which we can call the sp.bincount() function on.

推荐答案

没有更多信息,您的代码将无法运行.我认为您想要类似功能networkx.get_node_attributes():

Your code won't run without more info. I think you want something like the function networkx.get_node_attributes():

In [1]: import networkx as nx

In [2]: G = nx.Graph()

In [3]: G.add_node(1,profit=17)

In [4]: G.add_node(2,profit=42)

In [5]: a = nx.get_node_attributes(G,'profit')

In [6]: a.items()
Out[6]: [(1, 17), (2, 42)]

这篇关于如何使用Python从NetworkX中的特定节点属性获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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