简体   繁体   中英

Networkx python calculating weights

So i have the following data:

  9 22 1 1082418256   
  5 21 1 1082434689  
  26 7 1 1082448725  
  27 28 1 1082457840  
  29 25 1 1082471683  
  30 31 1 1082485106  
  30 31 1 1082485111  
  30 31 1 1082485113  
  30 31 1 1082485116  
  32 33 1 1082485623  
  34 35 1 1082493130

First column is node_from, second is node_to, 3rd is weight (default is 1), and the last column is timestamp.

My question is how can i calculate weight based on number of links between 2 nodes. For example row

30 31 1 1082485116

should have weight 4 because there has been connection between these 2 nodes 4 times.

Thanks in advance! This is the link to network with file below:

You can build the graph incrementally and just keep adding the weights to the edge, eg:

In []
import networkx as nx

G = nx.Graph()
with open(<file>) as file:
    for line in file:
        e1, e2, weight, timestamp = line.strip().split()
        G.add_edge(e1, e2)
        G[e1][e2]['weight'] = G[e1][e2].get('weight', 0) + int(weight)

nx.to_dict_of_dicts(G)

Out[]:
{'9': {'22': {'weight': 1}},
 '22': {'9': {'weight': 1}},
 '5': {'21': {'weight': 1}},
 '21': {'5': {'weight': 1}},
 '26': {'7': {'weight': 1}},
 '7': {'26': {'weight': 1}},
 '27': {'28': {'weight': 1}},
 '28': {'27': {'weight': 1}},
 '29': {'25': {'weight': 1}},
 '25': {'29': {'weight': 1}},
 '30': {'31': {'weight': 4}},
 '31': {'30': {'weight': 4}},
 '32': {'33': {'weight': 1}},
 '33': {'32': {'weight': 1}},
 '34': {'35': {'weight': 1}},
 '35': {'34': {'weight': 1}}}

If you are willing to use additional libraries then you could create an edge list in pandas and convert to a graph:

import pandas as pd

cols = ['source', 'target', 'weight', 'timestamp']
with open(<file>) as file:
    df = pd.read_csv(file, sep=' ', header=None, names=cols).drop('timestamp', axis=1)
G = nx.from_pandas_edgelist(df.groupby([df.source, df.target]).sum().reset_index(),  edge_attr=True)

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