1
votes

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)

1
Your variable i should contain the name of the neighbour.Sparky05
To expand on @Sparky05' comment: print(i, G.edges[('Rochester, NY',i)]).Paul Brodersen
@PaulBrodersen thank you that worked. A follow up to this would be- how can i translate this into a function with an input of multiple cities (nodes). For example, 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. Any help is much appreciatedT. Rama

1 Answers

0
votes

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)