Lee Yaan
Lee Yaan

Reputation: 547

How to find the negative weight between two adjacent nodes in python

Hi i have a big text file with format like this:

1  3  1
2  3  -1
5  7  1
6  1  -1
3  2  -1

the first column is the starting node, the second column the ending node and the third column shows the sign between two nodes. So i have positive and negative signs. Im reading the graph with the code below:

G = nx.Graph()
G = nx.read_edgelist('network.txt', delimiter='\t', nodetype=int, data=(('weight', int),))
print(nx.info(G))

I also found a function to find the neighbors of a specific node:

list1 = list(G.neigbors(1))

So i have a list with the adjacency nodes of node 1. How can a find the sign between the node 1 and each adjacency node? (For example that edge between 1-3 has sign 1, the edge 1-5 has sign -1 etc)

Upvotes: 0

Views: 86

Answers (1)

grovina
grovina

Reputation: 3077

An example for node 1:

n_from = 1
for n_to in G.neighbors(n_from):
    sign = G[n_from][n_to]['weight']

    print('edge from {} to {} has sign {}'.format(
        n_from, n_to, sign))

which prints, for the example input you gave:

edge from 1 to 3 has sign 1
edge from 1 to 6 has sign -1

A similar approach, treating G[n_from] as a dict:

n_from = 1
for n_to, e_data in G[n_from].items():
    sign = e_data['weight']
    # then print

You can alternatively use Graph.get_edge_data, as such:

e_data = G.get_edge_data(n_from, n_to)
sign = e_data.get('weight')

Upvotes: 1

Related Questions