Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edge weight in networkx

How do I assign to each edge a weight equals to the number of times node i and j interacted from an edge list?

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
import scipy.sparse

df = pd.read_csv("thiers_2011.csv", header = None)
df = df.rename(columns={0: "t", 1: "id1", 2: "id2", 3: "C1", 4: "C2"})

edge_list = np.zeros((len(df),2))
edge_list[:,0] = np.array(df["id1"]) 
edge_list[:,1] = np.array(df["id2"]) 

G = nx.Graph()
G.add_edges_from(edge_list)
like image 790
Kausutua Tjikundi Avatar asked Nov 15 '25 14:11

Kausutua Tjikundi


1 Answers

You can first aggregate the pandas tables to have a weight column, and then load it to networkx with that edge column:

df["weight"] = 1.0
df = df.groupby([<id_columns>]).agg({"wight": sum}).reset_index()

To load it you can use also from_pandas_edgelist:

G = nx.from_pandas_edgelist(source='source_column', target='target_column', edge_attr="weight")
like image 102
Eyal Asulin Avatar answered Nov 18 '25 03:11

Eyal Asulin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!