简体   繁体   中英

Python - Networkx: Graph of Neighbor Nodes with certain weight

The following problem is using Python 3.9 and Networkx 2.5

I need to output a subgraph of G that only contains edges between nodes in a list and directly neighboring nodes with edge weights less than 100. Currently I am using the following code, but only am able to pull the edge weight. I need to get both the node name and edge weight.

list_neighbors=G.neighbors('Rochester, NY')
for i in list_neighbors:
    if G.edges[('Rochester, NY',i)]['weight']<100:
        print (G.edges[('Rochester, NY',i)])

OUTPUT: {'weight': 88}

How do I get the output to include the Node Names as well (input node and it's neighbor that meets criteria of weight)

I would like to have the input of the function be ('Rochester, NY', 'Seattle, WA'), and the output to be the neighbor cities of each within 100 miles.

Follow up questions are discouraged in favour of new, separate question but since you are new here:

import networkx as nx

# version 1 : outputs an iterator; more elegant, potentially more performant (unlikely in this case though)
def get_neighbors_below_threshold(graph, node, threshold=100, attribute='weight'):
    for neighbor in graph.neighors(node):
        if graph.edges[(node, neighbor)][attribute] < threshold:
            yield neighbor

# version 2 : outputs a list; maybe easier to understand
def get_neighbors_below_threshold(graph, node, threshold=100, attribute='weight'):
    output = []
    for neighbor in graph.neighors(node):
        if graph.edges[(node, neighbor)][attribute] < threshold:
            output.append(neighbor)
    return output


n1 = get_neighbors_below_threshold(G, 'Rochester, NY')
n2 = get_neighbors_below_threshold(G, 'Seattle, WA')

combined_neighbors = set(n1) | set(n2)
common_neighbors = set(n1) & set(n2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM