user3685918
user3685918

Reputation: 427

Add weights from same edges before creating NetworkX graph

I have a dataframe as follows and I work a directed Graph.

In this case, You can find that there are same interactions between '1' and '3' in the first and last lines.

I find that nx.degree() function is only applied the last event of same nodes' interactions.

I would like to get degree() considering all the event between same nodes in the networkx syntax.

  sender receiver  amt
0      1        3   50
3      2        1    1
4      1        3  100
test = pd.DataFrame({'sender' : ['1','2','1'], 
                   'receiver' : ['3','1','3'], 
                   'amt' : [50,1,100]})

H = nx.from_pandas_edgelist(test, source = 'sender', target = 'receiver',
                            create_using=nx.DiGraph(), edge_attr = 'amt')

H.out_degree(weight = 'amt')
# this is a result :  {'1': 100, '3': 0, '2': 1}
# However I want to get this result : {'1': 150, '3': 0, '2': 1}

Upvotes: 1

Views: 194

Answers (1)

yatu
yatu

Reputation: 88226

You're getting that out degree because only the last edge is considered. You cannot have multiple edges connecting to the same ends in a directed graph. Considering the output you expect, what you can do is groupby and sum those weights beforehand:

G = nx.from_pandas_edgelist(test.groupby(['sender','receiver'], as_index=False).amt.sum(), 
                            source = 'sender', 
                            target = 'receiver',
                            create_using=nx.DiGraph(), 
                            edge_attr = 'amt')

G.out_degree(weight = 'amt')
# OutDegreeView({1: 150, 3: 0, 2: 1})

Upvotes: 1

Related Questions