Best practices for Querying graphs by edge and node attributes in NetworkX

前端 未结 3 743
野性不改
野性不改 2020-12-04 11:38

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 creat

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 12:08

    In order to select edges based on attributes of edges AND nodes, you may want to do something like this, using your graph, G2:

    def select(G2, query):
        '''Call the query for each edge, return list of matches'''
        result = []
        for u,v,d in G2.edges(data=True):
            if query(u,v,d):
                result.append([(u,v)])
        return result
    
    # Example query functions
    # Each assumes that it receives two nodes (u,v) and 
    # the data (d) for an edge 
    
    def dog_feeling(u, v, d):
        return (d['statementid'] == "3" 
                and G2.node[u]['type'] == "Dog"
                or G2.node[u]['type'] == "Dog")
    
    def any_feeling(u,v,d):
        return (d['statementid'] == "3" 
                and G2.node[u]['type'] == "Feeling"
                or G2.node[u]['type'] == "Feeling")
    
    def cat_feeling(u,v,d):
        return (G2.node[u]['type'] == "Cat"
                or G2.node[v]['type'] == "Cat")
    
    # Using the queries
    print select(G2, query = dog_feeling)
    print select(G2, query = any_feeling)
    print select(G2, query = cat_feeling)
    

    This abstracts away the iteration process into the select() function and you can write your queries as individual, testable functions.

提交回复
热议问题