I load text file of weighted graph. The text file contains three columns named "FromNodeId", "ToNodeId" and "Sign". Sign is weight of edge. value of Sign is -1 or 1. I want to find the number of output edges (output degree) with the "Sign=1" of each node. Please suggest me a way to solve this problem.
import networkx as nx
G= nx.read_edgelist("soc-sign-epinions.txt",data = [('Sign', int)], create_using=nx.DiGraph())
nodes = G.nodes()
edges = G.edges()
You can do this directly using pandas. You can read in your data using pd.read_csv('path_to_file'), then filter for edges with positive sign, then groupby origin node and sum up the remaining signs. Here is an example with fake data:
import pandas as pd
data=pd.DataFrame([['a','b',1],
['a','c',-1],
['a','d',1],
['b','a',1],
['b','d',-1],
['c','a',1],
['d','b',1]],
columns = ["FromNodeId", "ToNodeId","Sign"])
data[data['Sign']==1].groupby('FromNodeId')['Sign'].sum()
returns:
FromNodeId
a 2
b 1
c 1
d 1
Name: Sign, dtype: int64
So we'll break this down into two observations. First we can access all the edges out of a node (and the associated data) with G.edges(node, data = True)
. Second, there are ways to efficiently loop through these edges just counting those with positive sign. More generally, this approach can be used to count the number of edges out of a node that have any particular property.
import networkx as nx
G = nx.DiGraph()
G.add_edge(0,2,sign=-1)
G.add_edge(0,1, sign = 1)
G.add_edge(2,3,sign = 1)
G.add_edge(3,0, sign=-1)
print(G.edges(0, data=True))
>[(0, 2, {'sign': -1}), (0, 1, {'sign': 1})]
Note that the edge (3,0) did not appear here. So G.edges(0, data=True)
results in the edges that start from 0
and includes the data you've attached to the edge. (in your final code, obviously you don't actually want this print statement).
Now we'll use that in a generator and sum up the number of elements.
s = sum(1 for (u,v,d) in G.edges(0, data=True) if d['sign']==1)
print(s)
> 1
What I've done is create a generator that goes through all edges out of 0
and if the sign is 1
, it adds 1 to the output.
If that last sentence doesn't make sense, look at this answer: https://stackoverflow.com/a/7223557/2966723 to given an idea of what is going on, and for more about generators, start with Understanding generators in Python .
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.