在NetworkX中按边和节点属性查询图的最佳实践 [英] Best practices for Querying graphs by edge and node attributes in NetworkX

查看:295
本文介绍了在NetworkX中按边和节点属性查询图的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用NetworkX(是库中的新增功能)进行社交网络分析查询.通过查询,我的意思是通过两个边缘节点的属性选择/创建子图,其中边缘创建路径,并且节点包含属性.该图使用的形式为MultiDiGraph

Using NetworkX, and new to the library, for a social network analysis query. By Query, I mean select/create subgraphs by attributes of both edges nodes where the edges create a path, and nodes contain attributes. The graph is using a MultiDiGraph of the form

G2 = nx.MultiDiGraph()
G2.add_node( "UserA", { "type" :"Cat" } )
G2.add_node( "UserB", { "type" :"Dog" } )
G2.add_node( "UserC", { "type" :"Mouse" } )
G2.add_node( "Likes", { "type" :"Feeling" } )
G2.add_node( "Hates", { "type" :"Feeling" } )

G2.add_edge( "UserA", 'Hates' ,  statementid="1" )
G2.add_edge( "Hates", 'UserB' ,  statementid="1"  )
G2.add_edge( "UserC", 'Hates' ,  statementid="2" )
G2.add_edge( "Hates", 'UserA' ,  statementid="2"  )
G2.add_edge( "UserB", 'Hates' ,  statementid="3"  )
G2.add_edge( "Hates", 'UserA' ,  statementid="3"  )
G2.add_edge( "UserC", 'Likes' ,  statementid="3"  )
G2.add_edge( "Likes", 'UserB' ,  statementid="3"  )

被问及

for node,data in G2.nodes_iter(data=True):
    if ( data['type'] == "Cat" ):
       # get all edges out from these nodes
            #then recursively follow using a filter for a specific statement_id

#or get all edges with a specific statement id
   # look for  with a node attribute of "cat" 

是否有更好的查询方式?还是创建自定义迭代以创建子图的最佳实践?

Is there a better way to query? Or is it best practice to create custom iterations to create subgraphs?

或者(也可以作为一个单独的问题),可以简化图,但是我不使用下面的图,因为讨厌"类型的对象将具有前身.这会使查询更简单吗?似乎更容易遍历节点

Alternatively (and a separate question), the Graph could be simplified, but I'm not using the below graph because the "hates" type objects will have predcessors. Would this make querying simpler? Seems easier to iterate over nodes

G3 = nx.MultiDiGraph()
G3.add_node( "UserA", { "type" :"Cat" } )
G3.add_node( "UserB", { "type" :"Dog" } )

G3.add_edge( "UserA", 'UserB' ,  statementid="1" , label="hates")
G3.add_edge( "UserA", 'UserB' ,  statementid="2" , label="hates")

其他说明:

  • Perhaps add_path adds an identifier to the path created?
  • iGraph has a nice query feature g.vs.select()

推荐答案

基于 @Aric的答案,您可以找到像这样的红色鱼:

Building on @Aric's answer, you can find red fish like this:

red_fish = set(n for u,v,d in G.edges_iter(data=True)
               if d['color']=='red'
               for n in (u, v)
               if G.node[n]['label']=='fish')

print(red_fish)
# set([2])

这篇关于在NetworkX中按边和节点属性查询图的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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